Module: ActiveItem::ComposedOf::ClassMethods

Defined in:
lib/active_item/composed_of.rb

Instance Method Summary collapse

Instance Method Details

#composed_of(part_id, options = {}) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/active_item/composed_of.rb', line 140

def composed_of(part_id, options = {})
  class_name  = options[:class_name] || part_id.to_s.camelize
  mapping     = options[:mapping] || {}
  allow_nil   = options.fetch(:allow_nil, true)
  constructor = options.fetch(:constructor, :new)
  converter   = options[:converter]

  compositions[part_id] = { class_name: class_name, mapping: mapping, allow_nil: allow_nil,
                            constructor: constructor, converter: converter }

  define_method(part_id) do
    ivar = "@_composed_#{part_id}"
    return instance_variable_get(ivar) if instance_variable_defined?(ivar)

    vo_class = Object.const_get(class_name)
    values = mapping.map { |model_attr, _vo_attr| send(model_attr) }

    if allow_nil && values.all? { |v| v.nil? || (v.respond_to?(:empty?) && v.empty?) }
      instance_variable_set(ivar, nil)
      return nil
    end

    vo = if constructor.is_a?(Proc)
           constructor.call(*values)
         else
           kwargs = {}
           mapping.each { |model_attr, vo_attr| kwargs[vo_attr] = send(model_attr) }
           vo_class.send(constructor, **kwargs)
         end

    instance_variable_set(ivar, vo)
  end

  define_method("#{part_id}=") do |value|
    ivar = "@_composed_#{part_id}"

    if value.nil?
      mapping.each_key { |model_attr| send("#{model_attr}=", nil) }
      instance_variable_set(ivar, nil)
    elsif value.is_a?(Object.const_get(class_name))
      mapping.each { |model_attr, vo_attr| send("#{model_attr}=", value.send(vo_attr)) }
      instance_variable_set(ivar, value)
    elsif converter
      converted = converter.is_a?(Proc) ? converter.call(value) : Object.const_get(class_name).send(converter, value)
      send("#{part_id}=", converted)
    elsif value.is_a?(Hash)
      vo = Object.const_get(class_name).new(**value.transform_keys(&:to_sym))
      send("#{part_id}=", vo)
    else
      raise ArgumentError, "Cannot assign #{value.class} to #{part_id}. Expected #{class_name}, Hash, or nil."
    end
  end
end

#compositionsObject



136
137
138
# File 'lib/active_item/composed_of.rb', line 136

def compositions
  @_compositions ||= {}
end