Class: Composition::Compositions::Compose
- Inherits:
-
Composition
- Object
- Composition
- Composition::Compositions::Compose
- Defined in:
- lib/composition/compositions/compose.rb
Instance Attribute Summary
Attributes inherited from Composition
Instance Method Summary collapse
- #actual_column_for(aliased_attribute) ⇒ Object
-
#getter(ar) ⇒ Object
For a composition defined like:.
- #mapping ⇒ Object
-
#setter(ar, setter_value) ⇒ Object
For a composition defined like:.
Methods inherited from Composition
#class_name, #initialize, #inverse_of, #klass
Constructor Details
This class inherits a constructor from Composition::Compositions::Composition
Instance Method Details
#actual_column_for(aliased_attribute) ⇒ Object
56 57 58 |
# File 'lib/composition/compositions/compose.rb', line 56 def actual_column_for(aliased_attribute) mapping.key(aliased_attribute) end |
#getter(ar) ⇒ Object
For a composition defined like:
class User < ActiveRecord::Base
compose :credit_card,
mapping: {
credit_card_name: :name,
credit_card_brand: :brand
}
end
The getter method will be in charge of implementing @user.credit_card.
It is responsible for instantiating a new CreditCard object with the attributes from the de-normalized columns in User, and then return it.
19 20 21 22 |
# File 'lib/composition/compositions/compose.rb', line 19 def getter(ar) attributes = attributes(ar) klass.new(attributes.merge(composed_from.name => ar)).tap(&:valid?) unless all_blank?(attributes) end |
#mapping ⇒ Object
52 53 54 |
# File 'lib/composition/compositions/compose.rb', line 52 def mapping @options[:mapping] end |
#setter(ar, setter_value) ⇒ Object
For a composition defined like:
class User < ActiveRecord::Base
compose :credit_card,
mapping: {
credit_card_name: :name,
credit_card_brand: :brand
}
end
The setter method will be in charge of implementing @user.credit_card=.
setter_value can be either a credit_card instance or a hash of attributes and the setter will only set the @credit_card attributes that are included in the hash. This means that if a credit_card attribute is not given in the hash then we’ll set it with the value from the @user de-normalized column. The reason behind this is to imitate how ActiveRecord assign_attributes method works.
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/composition/compositions/compose.rb', line 41 def setter(ar, setter_value) nil_columns(ar) and return if setter_value.nil? attributes = setter_value.to_h.with_indifferent_access mapping.each do |actual_column, composed_alias| ar.send("#{actual_column}=", attributes[composed_alias]) if attributes.key?(composed_alias) end setter_value end |