Class: DumpedRailers::Import

Inherits:
Object
  • Object
show all
Defined in:
lib/dumped_railers/import.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*paths, authorized_models: [], before_save: [], after_save: [], yaml_column_permitted_classes: []) ⇒ Import

Returns a new instance of Import.



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/dumped_railers/import.rb', line 9

def initialize(*paths, authorized_models: [], before_save: [], after_save: [], yaml_column_permitted_classes: [])
  @before_save =  before_save
  @after_save  =  after_save

  if (paths.first.is_a? Hash)
    @raw_fixtures = paths.first.values
  else
    @raw_fixtures = FileHelper.read_fixtures(*paths, yaml_column_permitted_classes: yaml_column_permitted_classes)
  end

  @fixture_set = RecordBuilder::FixtureSet.new(@raw_fixtures, authorized_models: authorized_models)
end

Instance Attribute Details

#fixture_setObject (readonly)

Returns the value of attribute fixture_set.



7
8
9
# File 'lib/dumped_railers/import.rb', line 7

def fixture_set
  @fixture_set
end

Instance Method Details

#import_all!(&block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/dumped_railers/import.rb', line 22

def import_all!(&block)
  fixture_set.authorize_models!
  fixture_set.sort_by_table_dependencies!
  @record_sets = fixture_set.build_record_sets!

  ActiveRecord::Base.transaction(joinable: false, requires_new: true) do
    # models have to be persisted one-by-one so that dependent models are able to 
    # resolve "belongs_to" (parent) association
    @record_sets.each do |model, records|
      @before_save.each do |callback|
        callback.call(model, records)
      end
    end

    @record_sets.each do |model, records|
      # FIXME: faster implementation wanted, parhaps with activerocord-import
      # (objects needs to be reloaded somehow when using buik insert)
      records.each(&:save!)
    end

    @record_sets.each do |model, records|
      @after_save.each do |callback|
        callback.call(model, records)
      end
    end
  end
end