Sha256: e10b7e395bccbb8b1671bc5e54f1bad9ff7acaa2a4ac8e8674d17d7f00d739e2

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

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'

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
encore-0.0.3 lib/encore/association.rb