Class: Grub::Gemfile

Inherits:
Object
  • Object
show all
Defined in:
lib/grub/gemfile.rb

Constant Summary collapse

GEM_LINE_REGEX =
/\A\s*gem[\s(]+["'](?<name>[^'"]*)["']/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(gemfile_path, options = {}) ⇒ Gemfile

Returns a new instance of Gemfile.



8
9
10
11
12
13
# File 'lib/grub/gemfile.rb', line 8

def initialize(gemfile_path, options = {})
  @gemfile_path = gemfile_path
  @source = []
  @gem_lines = []
  @options = options
end

Instance Attribute Details

#gem_linesObject

Returns the value of attribute gem_lines.



6
7
8
# File 'lib/grub/gemfile.rb', line 6

def gem_lines
  @gem_lines
end

#gemfile_pathObject

Returns the value of attribute gemfile_path.



6
7
8
# File 'lib/grub/gemfile.rb', line 6

def gemfile_path
  @gemfile_path
end

#optionsObject

Returns the value of attribute options.



6
7
8
# File 'lib/grub/gemfile.rb', line 6

def options
  @options
end

#sourceObject

Returns the value of attribute source.



6
7
8
# File 'lib/grub/gemfile.rb', line 6

def source
  @source
end

Instance Method Details

#parseObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/grub/gemfile.rb', line 15

def parse
  self.source = File.readlines(gemfile_path)
  source.each_with_index do |line, i|
    if match = GEM_LINE_REGEX.match(line)
      prev_line = source[i - 1] if i > 0
      prev_line_comment = prev_line if is_line_a_comment?(prev_line)
      self.gem_lines << GemLine.new(
        name: match[:name],
        original_line: line,
        location: i,
        prev_line_comment: prev_line_comment,
        options: options
      )
    end
  end
end

#write_commentsObject



32
33
34
35
36
37
# File 'lib/grub/gemfile.rb', line 32

def write_comments
  gem_lines.reverse.each do |gem_line|
    source.insert(gem_line.location, gem_line.comment) if gem_line.should_insert?
  end
  File.write(gemfile_path, source.join)
end