Module: HairTrigger::MigrationReader

Defined in:
lib/hair_trigger/migration_reader.rb

Class Method Summary collapse

Class Method Details

.get_triggers(source, options) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hair_trigger/migration_reader.rb', line 7

def get_triggers(source, options)
  triggers = []
  if source.is_a?(String)
    # schema.rb contents... because it's auto-generated and we know
    # exactly what it will look like, we can safely use a regex
    source.scan(/^  create_trigger\(.*?\n  end\n\n/m).each do |match|
      trigger = instance_eval("generate_" + match.strip)
      triggers << trigger if options[:include_manual_triggers] || trigger.options[:generated]
    end
  else
    contents = File.read(source.filename)
    return [] unless contents =~ /(create|drop)_trigger/
    sexps = RubyParser.for_current_ruby.parse(contents)
    # find the migration class
    sexps = [sexps] unless sexps[0] == :block
    sexps = sexps.detect{ |s| s.is_a?(Sexp) && s[0] == :class && s[1] == source.name.to_sym }
    # find the block of the up method
    sexps = sexps.last if sexps.last.is_a?(Sexp) && sexps.last[0] == :block
    sexps = sexps.detect{ |s| s.is_a?(Sexp) && (s[0] == :defs && s[1] && s[1][0] == :self && s[2] == :up || s[0] == :defn && s[1] == :up) }
    return [] unless sexps # no `up` method... unsupported `change` perhaps?
    sexps.each do |sexp|
      next unless (method = extract_method_call(sexp)) && [:create_trigger, :drop_trigger].include?(method)
      trigger = instance_eval("generate_" + generator.process(sexp))
      triggers << trigger if options[:include_manual_triggers] || trigger.options[:generated]
    end
  end
  triggers
rescue
  $stderr.puts "Error reading triggers in #{source.filename rescue "schema.rb"}: #{$!}"
  []
end