Class: MongoMapper::Plugins::Associations::SingleAssociation

Inherits:
Base
  • Object
show all
Defined in:
lib/mongo_mapper/plugins/associations/single_association.rb

Direct Known Subclasses

BelongsToAssociation, OneAssociation

Constant Summary

Constants inherited from Base

Base::AssociationOptions

Instance Attribute Summary

Attributes inherited from Base

#name, #options, #query_options

Instance Method Summary collapse

Methods inherited from Base

#as, #as?, #autosave?, #class_name, #embeddable?, #foreign_key, #in_array?, #initialize, #ivar, #klass, #polymorphic?, #proxy_class, #touch?, #type_key_name

Constructor Details

This class inherits a constructor from MongoMapper::Plugins::Associations::Base

Instance Method Details

#setup(model) ⇒ Object



6
7
8
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
# File 'lib/mongo_mapper/plugins/associations/single_association.rb', line 6

def setup(model)
  @model = model
  model.associations_module.module_eval <<-end_eval
    def #{name}
      proxy = get_proxy(associations[#{name.inspect}])
      proxy.nil? ? nil : proxy
    end

    def #{name}=(value)
      association = associations[#{name.inspect}]
      proxy = get_proxy(association)

      if proxy.nil? || proxy.target != value
        proxy = build_proxy(association)
      end

      proxy.replace(value)
      value
    end

    def #{name}?
      get_proxy(associations[#{name.inspect}]).present?
    end

    def build_#{name}(attrs={})
      get_proxy(associations[#{name.inspect}]).build(attrs)
    end

    def create_#{name}(attrs={})
      get_proxy(associations[#{name.inspect}]).create(attrs)
    end

    def create_#{name}!(attrs={})
      get_proxy(associations[#{name.inspect}]).create!(attrs)
    end
  end_eval
end