Class: File
Class Method Summary collapse
-
.common_path(paths) ⇒ String
Returns the longest path that all of
pathshave in common. -
.edit_lines(filename, eol: $/) {|lines| ... } ⇒ Array<String>
Reads the entire contents of the file indicated by
filenameas an array of lines, and yields that array to the given block for editing. -
.edit_text(filename) {|text| ... } ⇒ String
Reads the entire contents of the file indicated by
filenameas a string, and yields that string to the given block for editing.
Class Method Details
.common_path(paths) ⇒ String
Returns the longest path that all of paths have in common.
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/pleasant_path/file.rb', line 14 def self.common_path(paths) return paths.first if paths.length <= 1 short, long = paths.minmax i = 0 last = -1 while i < short.length && short[i] == long[i] last = i if short[i] == "/" i += 1 end short[0, i == short.length ? i : (last + 1)] end |
.edit_lines(filename, eol: $/) {|lines| ... } ⇒ Array<String>
Reads the entire contents of the file indicated by filename as an array of lines, and yields that array to the given block for editing. Writes the return value of the block back to the file, overwriting previous contents. End-of-line (EOL) characters are stripped when reading, and appended after each line when writing. Returns the return value of the block.
78 79 80 81 82 83 84 85 86 |
# File 'lib/pleasant_path/file.rb', line 78 def self.edit_lines(filename, eol: $/) self.open(filename, "r+") do |f| lines = yield f.read_lines(eol: eol) f.seek(0, IO::SEEK_SET) f.write_lines(lines, eol: eol) f.truncate(f.pos) lines end end |
.edit_text(filename) {|text| ... } ⇒ String
Reads the entire contents of the file indicated by filename as a string, and yields that 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.
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 |