Class: File

Inherits:
Object show all
Defined in:
lib/pleasant_path/file.rb

Class Method Summary collapse

Class Method Details

.common_path(paths) ⇒ String

Computes the longest path that every path in a list has in common.

Examples:

File.common_path(["a/b/x", "a/b/y", "a/b/z"])  # == "a/b/"
File.common_path(["a/b/x", "a/b/y", "a/z"])    # == "a/"
File.common_path(["a/b/x", "a/b/y", "a"])      # == "a"

Parameters:

Returns:



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/pleasant_path/file.rb', line 12

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] == "/".freeze
    i += 1
  end
  short[0, i == short.length ? i : (last + 1)]
end

.edit_lines(filename) {|lines| ... } ⇒ Array<String>

Reads from the specified file its contents as an array of lines, and yields the array to the given block for editing. Writes the return value of the block back to the file, overwriting previous contents. The $/ global string specifies what end-of-line characters to use for both reading and writing. Returns the array of lines that comprises the file’s new contents.

Examples:

dedup lines of file

File.read("entries.txt")  # == "AAA\nBBB\nBBB\nCCC\nAAA\n"

File.edit_lines("entries.txt", &:uniq)
  # == ["AAA", "BBB", "CCC"]

File.read("entries.txt")  # == "AAA\nBBB\nCCC\n"

Parameters:

Yields:

  • (lines)

    edits current file contents

Yield Parameters:

Yield Returns:

Returns:



75
76
77
78
79
80
81
82
83
# File 'lib/pleasant_path/file.rb', line 75

def self.edit_lines(filename)
  self.open(filename, "r+") do |f|
    lines = yield f.read_lines
    f.seek(0, IO::SEEK_SET)
    f.write_lines(lines)
    f.truncate(f.pos)
    lines
  end
end

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

Reads from the specified file its contents as a string, and yields the string to the given block for editing. Writes the return value of the block back to the file, overwriting previous contents. Returns the file’s new contents.

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)

    edits current file contents

Yield Parameters:

  • text (String)

    current contents

Yield Returns:

Returns:



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

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