Module: Rares::Modules::TextFile

Included in:
Rares::Main
Defined in:
lib/rares/modules/text_file.rb

Instance Method Summary collapse

Instance Method Details

#clean_file!Object



70
71
72
# File 'lib/rares/modules/text_file.rb', line 70

def clean_file!
  @current_file_content = []
end

#file(path, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rares/modules/text_file.rb', line 4

def file(path, &block)
  @current_file_path = "#{current_dir}/#{path}"
  @current_file_content = File.file?(current_file_path) ? File.readlines(current_file_path) : []

  if File.file?(@current_file_path)
    puts "Will update file #{@current_file_path}"
  else
    puts "Will create file #{@current_file_path}"
  end

  yield

  File.open(current_file_path, "w+") do |f|
    f.puts(@current_file_content)
  end
end

#indent(value) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/rares/modules/text_file.rb', line 21

def indent(value)
  if block_given?
    current_value = @current_indent
    @current_indent = value
    yield
    @current_indent = current_value
  else
    @current_indent = value
  end
end

#put_after_line(content, line_matcher, offset = 0) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/rares/modules/text_file.rb', line 32

def put_after_line(content, line_matcher, offset=0)
  current_file_content.each_with_index do |row, ind|
    if this_row?(row, line_matcher)
      indent = row.count(' ') - row.lstrip.count(' ') + current_indent
      add_content!(content, ind + offset + 1, indent)
      return
    end
  end
end

#put_before_line(content, line_matcher, offset = 0) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/rares/modules/text_file.rb', line 42

def put_before_line(content, line_matcher, offset=0)
  current_file_content.each_with_index do |row, ind|
    if this_row?(row, line_matcher)
      indent = row.count(' ') - row.lstrip.count(' ') + current_indent
      add_content!(content, ind + offset - 1, indent)
      return
    end
  end
end

#put_to_beginning(content, offset = 0) ⇒ Object



62
63
64
# File 'lib/rares/modules/text_file.rb', line 62

def put_to_beginning(content, offset = 0)
  add_content!(content, offset, 0)
end

#put_to_end(content, offset = 0) ⇒ Object



66
67
68
# File 'lib/rares/modules/text_file.rb', line 66

def put_to_end(content, offset = 0)
  add_content!(content, @current_file_content.size + offset, 0)
end

#replace_line(content, line_matcher, offset = 0) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/rares/modules/text_file.rb', line 52

def replace_line(content, line_matcher, offset=0)
  current_file_content.each_with_index do |row, ind|
    if this_row?(row, line_matcher)
      indent = row.count(' ') - row.lstrip.count(' ')
      add_content!(content, ind + offset, indent, true)
      return
    end
  end
end