module Nuggets::File::ReplaceMixin

Public Instance Methods

replace(name[, create_if_missing]) { ... } → aString click to toggle source
replace(name[, create_if_missing]) { |content| ... } → aString

Replaces the contents of file name with the result of the block. Yields the file's contents to the block if requested. Returns the new content.

If create_if_missing is true and the file does not exist, it will be created.

# File lib/nuggets/file/replace_mixin.rb, line 40
def replace(name, create_if_missing = false, &block)
  open(name, create_if_missing && !exist?(name) ? 'w+' : 'r+') { |f|
    content = block.arity != 0 ? yield(f.read) : yield

    f.truncate(0)
    f.rewind

    f.print content

    content
  }
end