Class: Encore::Association

Inherits:
Attribute show all
Defined in:
lib/encore/association.rb,
lib/encore/association/has_one_association.rb,
lib/encore/association/has_many_association.rb

Direct Known Subclasses

HasManyAssociation, HasOneAssociation

Defined Under Namespace

Classes: HasManyAssociation, HasOneAssociation

Instance Attribute Summary

Attributes inherited from Attribute

#attribute, #column, #klass, #opts

Instance Method Summary collapse

Methods inherited from Attribute

#==, #eql?, #hash, #readonly?, #to_s

Constructor Details

#initialize(*args) ⇒ Association

Returns a new instance of Association.



3
4
5
6
7
8
9
10
11
12
# File 'lib/encore/association.rb', line 3

def initialize(*args)
  super

  # Create a temporary accessor to store new values
  @klass.send :attr_accessor, self.tmp_column_accessor

  # Add callback on `before_save` to apply new values
  association = self
  @klass.before_save lambda { association.apply(self) }
end

Instance Method Details

#apply(object) ⇒ Object

Apply the new value to the column and reset the temporary accessor



20
21
22
23
# File 'lib/encore/association.rb', line 20

def apply(object)
  object.send :"#{column_accessor}=", object.send(tmp_column_accessor)
  object.send :"#{tmp_column_accessor}=", nil
end

#assign(object, value) ⇒ Object

Store the value in a temporary accessor used by the ‘before_save` callback



15
16
17
# File 'lib/encore/association.rb', line 15

def assign(object, value)
  object.send :"#{tmp_column_accessor}=", value
end

#fetch(object) ⇒ Object

Return the value of the association



26
27
28
# File 'lib/encore/association.rb', line 26

def fetch(object)
  object.send :"#{column_accessor}"
end