Module: Seedlings::ActiveModel

Defined in:
lib/seedlings.rb

Overview

The base plugin for Seedlings: ActiveModel. Use this if the class to be seeded has an AREL-like query interface

Instance Method Summary collapse

Instance Method Details

#constraints_for(the_data) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/seedlings.rb', line 51

def constraints_for the_data
  constraints = []
  constraint_columns = options[:constrain] ? [options[:constrain]].flatten : [:id]
  unless the_data.keys & constraint_columns == constraint_columns
    puts "Couldn't find necessary constraints #{constraint_columns.inspect} in #{the_data.inspect}, skipping"
    return constraints
  end
  constraint_columns.each do |key|
    constraints << { key => the_data[key] } if the_data[key]
  end
  constraints
end

#find_and_update_model_with(the_data) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/seedlings.rb', line 69

def find_and_update_model_with the_data
  object = find_model_with the_data
  if object
    puts "FOUND: #{object.inspect}"
    if !options[:update_existing]
      puts "  * skipping update as per options[:update_existing]"
    else
      puts "  * updating with #{the_data}"
      object.update_attributes(the_data)
    end
  else
    puts "NEW OBJECT: #{klass}.new(#{the_data.inspect})"
    object = klass.new(the_data)
    object.save!
  end
  puts
  object
end

#find_model_with(the_data) ⇒ Object



64
65
66
67
# File 'lib/seedlings.rb', line 64

def find_model_with the_data
  finder = constraints_for(the_data).inject(klass) { |k, constraint| k.where(constraint) }
  finder.first
end