Module: BillysBilling::Association

Included in:
Base
Defined in:
lib/billys_billing/association.rb

Overview

Defines associations methods

Instance Method Summary collapse

Instance Method Details

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

Specifie a has many association



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/billys_billing/association.rb', line 27

def has_many(name, options={})
  class_name = options[:class_name] || name
  instances = []
  class_eval do
    define_method("#{name}=") do |list|
      class_object = "BillysBilling::#{class_name.to_s.classify}".constantize
      list.each do |attributes|
        if attributes.is_a?(class_object)
          instances << attributes 
        else
          instances << class_object.new(attributes)
        end
      end
      instance_variable_set("@#{name}", instances)
    end
    
    define_method(name) do
      instance_variable_get("@#{name}")
    end
  end
end

#has_one(name, options = {}) ⇒ Object

Specifie a has one association



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/billys_billing/association.rb', line 6

def has_one(name, options={})
  class_name = options[:class_name] || name
  class_eval do
    # Creating setter method
    define_method("#{name}=") do |attributes|
      class_object = "BillysBilling::#{class_name.to_s.classify}".constantize
      if attributes.is_a?(class_object)
        instance = attributes 
      else
        instance = class_object.new(attributes)
      end
      instance_variable_set("@#{name}", instance)
    end
    # Creating getter method
    define_method(name) do 
      instance_variable_get("@#{name}")
    end
  end
end