Module: Entasis::Relations::ClassMethods

Defined in:
lib/entasis/relations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(*relations) ⇒ Object

To complete the inverse relationship and tie two models togeter specify the belongs_to relationship.

Last argument can be an options hash:

class: provide a custom class name


62
63
64
65
66
67
68
69
70
71
72
# File 'lib/entasis/relations.rb', line 62

def belongs_to(*relations)
  options = relations.last.is_a?(Hash) ? relations.pop : {}

  relations.each do |relation|
    relation_model = options[:class] || relation.to_s.singularize.camelize

    self.belongings[relation_model] = relation
  end

  attr_accessor *relations
end

#has_many(*relations) ⇒ Object

Takes a list of relations. Speciefy each relation as a pluralization of corresponding class.

Last argument can be an options hash:

class: provide a custom class name

This macro will give each instance corresponding setter and getter methods. Passing a collection of corresponding instances of the given class will populate the collection. Passing hashes will try to instanciate new objects of the relation’s class.

To set the inverse association and tie the objects together specify the belongs_to relation in the other class.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/entasis/relations.rb', line 24

def has_many(*relations)
  options = relations.last.is_a?(Hash) ? relations.pop : {}

  relations.each do |relation|
    relation_model = options[:class] || relation.to_s.singularize.camelize

    self.class_eval <<-RUBY
      def #{relation}=(resources)
        @#{relation} = []

        resources.each do |resource|
          unless resource.is_a? #{relation_model}
            resource = #{relation_model}.new resource
          end

          if inverse_relation = resource.belongings[self.class.to_s]
            resource.send "\#{inverse_relation}=", self
          end

          @#{relation} << resource
        end
      end

      def #{relation}
        @#{relation} || []
      end
    RUBY
  end
end