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
40 def replace(name, create_if_missing = false, &block)
41   open(name, create_if_missing && !exist?(name) ? 'w+' : 'r+') { |f|
42     content = block.arity != 0 ? yield(f.read) : yield
43 
44     f.truncate(0)
45     f.rewind
46 
47     f.print content
48 
49     content
50   }
51 end