Method: File.edit_text

Defined in:
lib/pleasant_path/file.rb

.edit_text(filename) {|text| ... } ⇒ String

Reads the file indicated by filename, and yields the entire contents as a String to the given block for editing. Writes the return value of the block back to the file, overwriting previous contents. Returns the return value of the block.

Examples:

Update JSON data file

File.read("data.json")  # == '{"nested":{"key":"value"}}'

File.edit_text("data.json") do |text|
  data = JSON.parse(text)
  data["nested"]["key"] = "new value"
  data.to_json
end                     # == '{"nested":{"key":"new value"}}'

File.read("data.json")  # == '{"nested":{"key":"new value"}}'

Parameters:

Yields:

  • (text)

Yield Parameters:

Yield Returns:

Returns:



47
48
49
50
51
52
53
54
55
# File 'lib/pleasant_path/file.rb', line 47

def self.edit_text(filename)
  self.open(filename, "r+") do |f|
    text = yield f.read
    f.seek(0, IO::SEEK_SET)
    f.write(text)
    f.truncate(f.pos)
    text
  end
end