Module: ContentfulModel::Associations::ClassMethods

Defined in:
lib/contentful_model/associations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(classname) ⇒ Object

belongs_to is called on the child, and creates methods for mapping to the parent

Parameters:

  • classname (Symbol)

    the singular name of the parent

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/contentful_model/associations.rb', line 45

def belongs_to(classname)
  raise ArgumentError, "belongs_to requires a class name as a symbol" unless classname.is_a?(Symbol)
  define_method "#{classname}" do
    #this is where we need to return the parent class
    self.instance_variable_get(:"@#{classname}")
  end

  define_method "#{classname}=" do |instance|
    #this is where we need to set the class name
    self.instance_variable_set(:"@#{classname}",instance)
  end


end

#has_many(classname) ⇒ Object

has_many is called on the parent model, and sets an instance var on the child which is named the plural of the class this module is mixed into.

e.g class Foo

has_many :bars

end

Parameters:

  • classname (Symbol)

    the name of the child model, as a plural symbol



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

def has_many(classname)
  #define an instance method called the same as the arg passed in
  #e.g. bars()
  define_method "#{classname}" do
    # call bars() on super, and for each, call bar=(self)
    super().collect do |instance|
      instance.send(:"#{self.class.to_s.singularize.camelize(:lower)}=",self)
      #return the instance to the collect() method
      instance
    end
  end
end

#has_one(classname) ⇒ Object

has_one is called on the parent model, and sets a single instance var on the child it’s conceptually identical to ‘has_many()` which is named the singular of the class this module is mixed into



35
36
37
38
39
40
# File 'lib/contentful_model/associations.rb', line 35

def has_one(classname)
  define_method "#{classname}" do
    super().send(:"#{self.class.to_s.singularize.camelize(:lower)}=",self)
    instance
  end
end