Module: Foobara::Entity::Concerns::Mutations::ClassMethods

Defined in:
foobara-0.0.110/projects/entity/src/concerns/mutations.rb

Instance Method Summary collapse

Instance Method Details

#update_aggregate(object, value, type = object.class.model_type) ⇒ 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'foobara-0.0.110/projects/entity/src/concerns/mutations.rb', line 19

def update_aggregate(object, value, type = object.class.model_type)
  return value if object.nil?

  if type.extends?(BuiltinTypes[:model])
    element_types = type.element_types.element_types

    value.each_pair do |attribute_name, new_value|
      current_value = object.read_attribute(attribute_name)

      attribute_type = element_types[attribute_name]

      updated_value = update_aggregate(current_value, new_value, attribute_type)

      object.write_attribute(attribute_name, updated_value)
    end

    object
  elsif type.extends?(BuiltinTypes[:attributes])
    element_types = type.element_types

    object = object.dup
    object ||= {}

    value.each_pair do |attribute_name, new_value|
      current_value = object[attribute_name]
      attribute_type = element_types[attribute_name]

      updated_value = update_aggregate(current_value, new_value, attribute_type)

      object[attribute_name] = updated_value
    end

    object
  elsif type.extends?(BuiltinTypes[:tuple])
    # :nocov:
    raise "Tuple not yet supported"
    # :nocov:
  elsif type.extends?(BuiltinTypes[:associative_array])
    # :nocov:
    raise "Associated array not yet supported"
    # :nocov:
  elsif type.extends?(BuiltinTypes[:array])
    element_type = type.element_type

    value.map.with_index do |element, index|
      update_aggregate(object[index], element, element_type)
    end
  else
    value
  end
end