Class: ReeDao::PersistAssoc

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_dao/package/ree_dao/functions/persist_assoc.rb

Instance Method Summary collapse

Instance Method Details

#call(agg_root, assoc_dao, **opts) ⇒ Object



19
20
21
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
49
50
51
52
53
# File 'lib/ree_lib/packages/ree_dao/package/ree_dao/functions/persist_assoc.rb', line 19

def call(agg_root, assoc_dao, **opts)
  setter_method = if opts[:root_setter].nil?
    name = underscore(demodulize(agg_root.class.name))
    "#{name}_id="
  else
    "#{opts[:root_setter]}"
  end

  assoc_name = if opts[:child_assoc].nil?
    dto_class = assoc_dao
      .opts[:schema_mapper]
      .dto(:db_load)

    name = underscore(demodulize(dto_class.name))
    "#{name}s"
  else
    opts[:child_assoc]
  end

  agg_root.send(assoc_name).each do |child|
    if !child.respond_to?(setter_method)
      raise ArgumentError.new("#{child.class} does not respond to `#{setter_method}` method")
    end

    child.send(setter_method, agg_root.id)

    if child.id
      assoc_dao.update(child)
    else
      assoc_dao.put(child)
    end
  end

  nil
end