Class: DumpedRailers::FixtureBuilder::Record

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

Instance Method Summary collapse

Constructor Details

#initialize(record, model, preprocessors:) ⇒ Record

Returns a new instance of Record.



6
7
8
9
10
# File 'lib/dumped_railers/fixture_builder/record.rb', line 6

def initialize(record, model, preprocessors:)
  @record = record
  @model = model
  @preprocessors = preprocessors
end

Instance Method Details

#build!Object



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
38
39
40
41
# File 'lib/dumped_railers/fixture_builder/record.rb', line 12

def build!
  id = @record.id
  attributes = @record.attributes.deep_dup
  @preprocessors.each do |preprocessor|
    preprocessor.call(@model, attributes)
  end

  # convert "belong_to association" foreign keys into record-unique labels
  @model.reflect_on_all_associations.select(&:belongs_to?).each do |rel|
    # skip ignorables
    next unless attributes.has_key? rel.foreign_key.to_s

    if rel.polymorphic?
      class_name = attributes[rel.foreign_type.to_s]

      attributes[rel.name.to_s] = record_label_for(
        class_name,
        attributes.delete(rel.foreign_key.to_s),
        attributes.delete(rel.foreign_type.to_s)
      )
    else
      attributes[rel.name.to_s] = record_label_for(
        rel.class_name,
        attributes.delete(rel.foreign_key.to_s)
      )
    end
  end

  [record_label_for(@model.name, id), attributes]
end