Module: BraintreeRails::Association::ClassMethods

Defined in:
lib/braintree_rails/association.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(receiver) ⇒ Object



4
5
6
7
# File 'lib/braintree_rails/association.rb', line 4

def self.extended(receiver)
  receiver.singleton_class.send(:attr_accessor, :associations)
  receiver.associations = []
end

Instance Method Details

#belongs_to(name, options) ⇒ Object



18
19
20
21
22
# File 'lib/braintree_rails/association.rb', line 18

def belongs_to(name, options)
  associations << name
  define_association_reader(name, options)
  define_association_writer(name, options)
end

#define_association_reader(name, options) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/braintree_rails/association.rb', line 28

def define_association_reader(name, options)
  define_method(name) do
    if value = instance_variable_get("@#{name}")
      return value
    elsif options[:foreign_key] && value = send(options[:foreign_key])
      instance_variable_set("@#{name}", options[:class].new(value))
    end
  end
end

#define_association_writer(name, options) ⇒ Object



38
39
40
41
42
43
# File 'lib/braintree_rails/association.rb', line 38

def define_association_writer(name, options)
  define_method("#{name}=") do |value|
    value &&= options[:class].new(value)
    instance_variable_set("@#{name}", value)
  end
end

#has_many(name, options) ⇒ Object



13
14
15
16
# File 'lib/braintree_rails/association.rb', line 13

def has_many(name, options)
  associations << name
  define_association_reader(name, options.merge(:foreign_key => :presence))
end

#has_one(name, options) ⇒ Object



24
25
26
# File 'lib/braintree_rails/association.rb', line 24

def has_one(name, options)
  belongs_to(name, options)
end

#inherited(subclass) ⇒ Object



9
10
11
# File 'lib/braintree_rails/association.rb', line 9

def inherited(subclass)
  subclass.associations = self.associations
end