Method: Methadone::CLI#add_to_file

Defined in:
lib/methadone/cli.rb

#add_to_file(file, lines, options = {}) ⇒ Object

Add content to a file

file

path to the file

lines

Array of String representing the lines to add

options

Hash of options:

:before

A regexp that will appear right after the new content. i.e. this is where to insert said content.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/methadone/cli.rb', line 37

def add_to_file(file,lines,options = {})
  new_lines = []
  found_line = false
  File.open(file).readlines.each do |line|
    line.chomp!
    if options[:before] && options[:before] === line
      found_line = true
      new_lines += lines
    end
    new_lines << line
  end

  raise "No line matched #{options[:before]}" if options[:before] && !found_line

  new_lines += lines unless options[:before]
  File.open(file,'w') do |fp|
    new_lines.each { |line| fp.puts line }
  end
end