Class: SeedFu::Seeder

Inherits:
Object
  • Object
show all
Defined in:
lib/seed-fu/seeder.rb

Overview

Creates or updates seed records with data.

It is not recommended to use this class directly. Instead, use Model.seed, and Model.seed_once, where Model is your Active Record model.

Instance Method Summary collapse

Constructor Details

#initialize(model_class, constraints, data, options = {}) ⇒ Seeder

Returns a new instance of Seeder

Options Hash (options):

  • :quiet (Boolean) — default: SeedFu.quiet

    If true, output will be silenced

  • :insert_only (Boolean) — default: false

    If true then existing records which match the constraints will not be updated, even if the seed data has changed



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/seed-fu/seeder.rb', line 20

def initialize(model_class, constraints, data, options = {})
  @model_class = model_class
  @constraints = constraints.to_a.empty? ? [:id] : constraints
  @data        = data.to_a || []
  @options     = options.symbolize_keys

  @options[:quiet] ||= SeedFu.quiet

  validate_constraints!
  validate_data!
end

Instance Method Details

#seedArray<ActiveRecord::Base>

Insert/update the records as appropriate. Validation is skipped while saving.



34
35
36
37
38
39
40
# File 'lib/seed-fu/seeder.rb', line 34

def seed
  records = @model_class.transaction do
    @data.map { |record_data| seed_record(record_data.symbolize_keys) }
  end
  update_id_sequence
  records
end