Module: Stairs::Util::FileMutation

Defined in:
lib/stairs/util/file_mutation.rb

Class Method Summary collapse

Class Method Details

.remove(pattern, filename) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/stairs/util/file_mutation.rb', line 18

def remove(pattern, filename)
  return unless File.exists? filename

  contents = File.read filename
  if contents =~ pattern
    contents.slice!(pattern)
    write contents, filename
  end
end

.replace_or_append(pattern, string, filename) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/stairs/util/file_mutation.rb', line 5

def replace_or_append(pattern, string, filename)
  if File.exists? filename
    contents = File.read filename
    if contents =~ pattern
      contents.sub! pattern, string
      write contents, filename
      return
    end
  end

  write_line string, filename
end

.write(string, filename) ⇒ Object



38
39
40
41
42
# File 'lib/stairs/util/file_mutation.rb', line 38

def write(string, filename)
  File.open filename, "w+" do |file|
    file.puts string
  end
end

.write_line(string, filename) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/stairs/util/file_mutation.rb', line 28

def write_line(string, filename)
  File.open filename, "a+" do |file|
    # ensure file ends with newline before appending
    last_line = file.each_line.reduce("") { |m, l| m = l }
    file.puts "" unless last_line == "" || last_line =~ /(.*)\n/

    file.puts string
  end
end