Class: SeedOMatic::Seeder

Inherits:
Object
  • Object
show all
Defined in:
lib/seedomatic/seeder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Seeder

Returns a new instance of Seeder.



6
7
8
9
10
11
# File 'lib/seedomatic/seeder.rb', line 6

def initialize(data)
  @model_name = data[:model_name]
  @items = data[:items]
  @match_on = [*data[:match_on]]
  @seed_mode = data[:seed_mode] || "always"
end

Instance Attribute Details

#itemsObject

Returns the value of attribute items.



4
5
6
# File 'lib/seedomatic/seeder.rb', line 4

def items
  @items
end

#match_onObject

Returns the value of attribute match_on.



4
5
6
# File 'lib/seedomatic/seeder.rb', line 4

def match_on
  @match_on
end

#model_nameObject

Returns the value of attribute model_name.



4
5
6
# File 'lib/seedomatic/seeder.rb', line 4

def model_name
  @model_name
end

#seed_modeObject

Returns the value of attribute seed_mode.



4
5
6
# File 'lib/seedomatic/seeder.rb', line 4

def seed_mode
  @seed_mode
end

Instance Method Details

#importObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/seedomatic/seeder.rb', line 13

def import
  new_records = 0
  updated_records = 0

  items.each do |attrs|
    model = model_class.unscoped.send(create_method, create_args(attrs))

    if model.new_record?
      new_records += 1
    else
      updated_records += 1
    end

    if model.new_record? || seed_mode == 'always'
      clean_up_associations(model, attrs)
      model.attributes = process_lookups(attrs)
      if !model.save
        raise "Unable to save model: #{model} - #{model.errors.full_messages.join(", ")}"
      end
    end
  end

  { :count => items.length, :new => new_records, :updated => updated_records}
end