Class: Nextgen::TidyGemfile

Inherits:
Object
  • Object
show all
Defined in:
lib/nextgen/tidy_gemfile.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = "Gemfile") ⇒ TidyGemfile

Returns a new instance of TidyGemfile.



11
12
13
14
# File 'lib/nextgen/tidy_gemfile.rb', line 11

def initialize(path = "Gemfile")
  @path = path
  @gemfile = File.read(path)
end

Class Method Details

.clean!(path = "Gemfile") ⇒ Object



5
6
7
8
9
# File 'lib/nextgen/tidy_gemfile.rb', line 5

def self.clean!(path = "Gemfile")
  gemfile = new(path)
  gemfile.clean
  gemfile.save
end

Instance Method Details

#add(gem, version: nil, group: nil, require: nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/nextgen/tidy_gemfile.rb', line 30

def add(gem, version: nil, group: nil, require: nil)
  return false if include?(gem)

  gem_line = build_gem_line(gem, version:, require:, indent: group ? "  " : "")

  if group
    group_line = create_group_if_needed(group)
    gemfile.sub!(/#{Regexp.quote(group_line)}/, '\0' + gem_line)
  else
    gemfile.sub!(/^(#|gem\s)/, gem_line + '\0')
  end

  # Add a blank line after the gem if the subsequent line starts with a comment
  gemfile.sub!(/(#{Regexp.quote(gem_line)})(\s*#)/, "\\1\n\\2")
  true
end

#cleanObject



20
21
22
23
24
25
26
27
28
# File 'lib/nextgen/tidy_gemfile.rb', line 20

def clean
  @gemfile = gemfile
    .gsub(/^\s*#.*/, "")          # remove comments
    .gsub(/(\s*\n)+/, "\n")       # remove blank lines
    .sub(/^(ruby.*)/, "\n\\1")    # ensure blank space before "ruby" line
    .sub(/^(gem.*)/, "\n\\1")     # ensure blank space before first "gem" line
    .gsub(/^(group.*)/, "\n\\1")  # ensure blank space before each "group" block
  nil
end

#include?(gem) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/nextgen/tidy_gemfile.rb', line 16

def include?(gem)
  gemfile.match?(/^\s*gem\s+['"]#{gem}['"]/)
end

#remove(gem) ⇒ Object



47
48
49
# File 'lib/nextgen/tidy_gemfile.rb', line 47

def remove(gem)
  !!gemfile.gsub!(/^( *#.*?\n)?\s*gem\s+['"]#{gem}['"].*\n/, "")
end

#saveObject



51
52
53
54
# File 'lib/nextgen/tidy_gemfile.rb', line 51

def save
  File.write(@path, gemfile.rstrip + "\n")
  true
end