Class: Formed::FromModel::FromModelAssignment

Inherits:
Object
  • Object
show all
Defined in:
lib/formed/from_model.rb

Class Method Summary collapse

Class Method Details

.call(instance, record) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/formed/from_model.rb', line 6

def self.call(instance, record)
  record.attributes.each do |k, v|
    instance.public_send("#{k}=", v) if instance.attributes.key?(k)
  end
  record._reflections.each do |attr, _record_reflection|
    next unless (form_reflection = instance._reflections[attr])

    case form_reflection.macro
    when :has_one
      instance.send("build_#{attr}").from_model(record.public_send(attr))
    when :has_many
      record.public_send(attr).each do |associated_record|
        instance.public_send(attr).build.from_model(associated_record)
      end
    end
  end

  instance.id = record.id
  instance.map_model(record)
  instance
end