Module: Glamazon::Associations

Defined in:
lib/glamazon/associations.rb

Defined Under Namespace

Classes: HasMany

Instance Method Summary collapse

Instance Method Details

#belongs_to(association, options = {}) ⇒ Object Also known as: has_one



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/glamazon/associations.rb', line 19

def belongs_to(association, options = {})
  klass = (options[:class] || association).to_s.classify
  define_method(association) { instance_variable_get :"@__#{association}__" }
  define_method("#{association}=") do |object|
    if object.instance_of? klass.classify.constantize
      instance_variable_set :"@__#{association}__", object
    else
      raise Glamazon::AssociationTypeMismatch.new "Object is of incorrect type. Must be an instance of #{@class}."
    end
  end 
end

#has_many(association, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/glamazon/associations.rb', line 9

def has_many(association, options = {})
  klass = options[:class]
  define_method association do
    unless ivar = instance_variable_get(:"@__#{association}__")
      instance_variable_set :"@__#{association}__", Glamazon::Associations::HasMany.new(association, self, klass, options)
    else
      ivar
    end
  end
end