Module: DataMapper::Associations::ManyToOne

Extended by:
DataMapper::Assertions
Defined in:
lib/gems/dm-core-0.9.9/lib/dm-core/associations/many_to_one.rb

Defined Under Namespace

Classes: Proxy

Class Method Summary collapse

Methods included from DataMapper::Assertions

assert_kind_of

Class Method Details

.setup(name, model, options = {}) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Setup many to one relationship between two models -



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/gems/dm-core-0.9.9/lib/dm-core/associations/many_to_one.rb', line 9

def self.setup(name, model, options = {})
  assert_kind_of 'name',    name,    Symbol
  assert_kind_of 'model',   model,   Model
  assert_kind_of 'options', options, Hash

  repository_name = model.repository.name

  model.class_eval <<-EOS, __FILE__, __LINE__
    def #{name}
      #{name}_association.nil? ? nil : #{name}_association
    end

    def #{name}=(parent)
      #{name}_association.replace(parent)
    end

    private

    def #{name}_association
      @#{name}_association ||= begin
        unless relationship = model.relationships(#{repository_name.inspect})[:#{name}]
          raise ArgumentError, "Relationship #{name.inspect} does not exist in \#{model}"
        end
        association = Proxy.new(relationship, self)
        child_associations << association
        association
      end
    end
  EOS

  model.relationships(repository_name)[name] = Relationship.new(
    name,
    repository_name,
    model,
    options.fetch(:class_name, Extlib::Inflection.classify(name)),
    options
  )
end