Class: ArelConverter::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/arel_converter/base.rb

Direct Known Subclasses

ActiveRecordFinder, Association, Scope

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, options = {}) ⇒ Base

Returns a new instance of Base.



6
7
8
9
# File 'lib/arel_converter/base.rb', line 6

def initialize(path, options = {})
  @path    = path
  @options = {dry_run: false}.merge(options)
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



4
5
6
# File 'lib/arel_converter/base.rb', line 4

def options
  @options
end

Instance Method Details

#grep_matches_in_file(file) ⇒ Object



65
66
67
# File 'lib/arel_converter/base.rb', line 65

def grep_matches_in_file(file)
  [] # abstract method overriden by subclasses
end

#parse_directory(path) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/arel_converter/base.rb', line 15

def parse_directory(path)
  Dir[File.join(path, '**/*.rb')].each do |file|
    begin
      parse_file(file)
    rescue => e
      Formatter.alert(file, [])
    end
  end
end

#parse_file(file) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/arel_converter/base.rb', line 25

def parse_file(file)

  lines_to_process = grep_matches_in_file(file)

  return if lines_to_process.empty?

  replacements = process_lines(lines_to_process)

  unless (replacements.nil? || replacements.empty?)
    Formatter.alert(file, replacements)
    update_file(file, replacements) unless @options[:dry_run]
  end
end

#process_lines(lines) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/arel_converter/base.rb', line 39

def process_lines(lines)
  lines.map do |line|
    r = Replacement.new(line)
    begin
      next unless verify_line(line)
      r.new_content = process_line(line)
    rescue SyntaxError => e
      r.error = "SyntaxError when evaluating options for #{line}"
    rescue Exception => e
      r.error = "#{e.class} #{e.message} when evaluating options for \"#{line}\"\n#{e.backtrace.first}"
    end
    r
  end.compact
end

#run!Object



11
12
13
# File 'lib/arel_converter/base.rb', line 11

def run!
  File.directory?(@path) ? parse_directory(@path) : parse_file(@path)
end

#update_file(file, line_replacements) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/arel_converter/base.rb', line 54

def update_file(file, line_replacements)
  contents = File.read(file)
  line_replacements.each do |r|
    contents.gsub!(r.old_content, r.new_content) if r.valid?
  end

  File.open(file, 'w') do |f|
    f.puts contents
  end
end