module Encore class Association < Attribute 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 # Store the value in a temporary accessor used by the `before_save` callback def assign(object, value) object.send :"#{tmp_column_accessor}=", value end # Apply the new value to the column and reset the temporary accessor def apply(object) object.send :"#{column_accessor}=", object.send(tmp_column_accessor) object.send :"#{tmp_column_accessor}=", nil end # Return the value of the association def fetch(object) object.send :"#{column_accessor}" end protected def tmp_column_accessor :"encore_tmp_#{column_accessor}" end end end require 'encore/association/has_one_association' require 'encore/association/has_many_association'