class Eefgilm::Gemfile

Attributes

groups[RW]
path[RW]
rubyversion[RW]
source[RW]

Public Class Methods

new(path = '.', options = {}) click to toggle source
# File lib/eefgilm/gemfile.rb, line 5
def initialize(path = '.', options = {})
  @path = path
  @groups = {}
  @options = {
    alphabetize: true,
    delete_whitespace: true,
    delete_comments: true
  }.merge(options)
end

Public Instance Methods

clean!() click to toggle source
# File lib/eefgilm/gemfile.rb, line 15
def clean!
  # Extract:
  extract_to_array_of_lines

  # Transform:
  change_double_qoutes_to_single if @options[:alphabetize]
  delete_comments! if @options[:delete_comments]
  delete_whitespace! if @options[:delete_whitespace]
  alphabetize_gems! if @options[:alphabetize]

  # Load:
  recreate_file
end

Private Instance Methods

alphabetize_gems!() click to toggle source
# File lib/eefgilm/gemfile.rb, line 101
def alphabetize_gems!
  @groups.each do |group, gems|
    @groups[group] = gems.sort
  end
end
change_double_qoutes_to_single() click to toggle source
# File lib/eefgilm/gemfile.rb, line 61
def change_double_qoutes_to_single
  @groups.each do |group, gems|
    @groups[group] = gems.map do |g|
      g.tr("\"", "'")
    end
  end
end
delete_comments!() click to toggle source
# File lib/eefgilm/gemfile.rb, line 69
def delete_comments!
  @groups.each do |group, gems|
    @groups[group] = gems.map do |g|
      g.gsub(/#(.*)$/, '')
    end
  end
end
delete_whitespace!() click to toggle source
# File lib/eefgilm/gemfile.rb, line 107
def delete_whitespace!
  @groups.each do |group, gems|
    @groups[group] = gems.map do |g|
      g.gsub(/(?<=^|\[)\s+|\s+(?=$|\])|(?<=\s)\s+/, '')
    end
  end
end
extract_to_array_of_lines() click to toggle source
# File lib/eefgilm/gemfile.rb, line 31
def extract_to_array_of_lines
  gemfile = File.open("#{@path}/Gemfile", 'r+')
  group_block = :all
  file_lines = gemfile.readlines

  file_lines.each do |line|
    self.source = line if line.match(/^source/)

    if source == "source 'http://rubygems.org'\n"
      self.source = "source 'https://rubygems.org'\n"
    end

    self.rubyversion = line if line.match(/^ruby/)

    if line.match(/^\s*group/)
      group_block = line.match(/^group (:.*)[,|\s]/)[1]
    elsif line.match(/^\s*end/)
      group_block = :all
    end

    if line.match(/^\s*gem/)
      if groups[group_block].nil?
        groups[group_block] = [line]
      else
        groups[group_block] << line
      end
    end
  end
end
recreate_file() click to toggle source
# File lib/eefgilm/gemfile.rb, line 77
def recreate_file
  output = File.open("#{@path}/Gemfile", 'w+')
  output.puts [@source, @rubyversion].compact
  output.puts

  @groups.each do |group, gems|
    if group == :all
      gems.each do |g|
        output.puts g
      end
    else
      output.puts
      output.puts "group #{group}"

      gems.each do |g|
        output.puts "  #{g}"
      end
      output.puts 'end'
    end
  end

  output.close
end