module Consumerable::Associations::BelongsTo::ClassMethods

Public Instance Methods

belongs_to(association_name, options = {}) click to toggle source
# File lib/consumerable/associations/belongs_to.rb, line 7
def belongs_to(association_name, options = {})
  foreign_key = options[:foreign_key] || :"#{association_name}_id"

  class_eval do
    attribute foreign_key, String
  end

  (class << self; self; end).instance_eval do
    define_method "_for_#{association_name}" do |id|
      init_collection Consumerable::Connection.
        get(list_path.gsub(/:#{association_name}_id/, id))
    end
  end

  define_method association_name do
    instance_variable_get(:"@#{association_name}") ||
      if self.send(foreign_key)
        options[:class_name].constantize.
          find(self.send(foreign_key)).tap do |parent|
            self.send("#{association_name}=", object)
          end
      else
        nil
      end
  end

  define_method "#{association_name}=" do |associated_object|
    instance_variable_set(:"@#{association_name}", associated_object)
    id = associated_object ? associated_object.id : nil
    self.send "#{foreign_key}=", id
  end
end