Module: Mongoid::Relations::Accessors::ClassMethods

Defined in:
lib/mongoid/relations/accessors.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#getter(name, metadata) ⇒ Class

Defines the getter for the relation. Nothing too special here: just return the instance variable for the relation if it exists or build the thing.

Examples:

Set up the getter for the relation.

Person.getter("addresses", )

Parameters:

  • name (String, Symbol)

    The name of the relation.

  • metadata (Metadata)

    The metadata for the relation.

Returns:

  • (Class)

    The class being set up.

Since:

  • 2.0.0.rc.1



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/mongoid/relations/accessors.rb', line 92

def getter(name, )
  tap do
    define_method(name) do |*args|
      reload, variable = args.first, "@#{name}"
      if instance_variable_defined?(variable) && !reload
        instance_variable_get(variable)
      else
        _building do
          _loading do
            build(name, attributes[.key], )
          end
        end
      end
    end
  end
end

#setter(name, metadata) ⇒ Class

Defines the setter for the relation. This does a few things based on some conditions. If there is an existing association, a target substitution will take place, otherwise a new relation will be created with the supplied target.

Examples:

Set up the setter for the relation.

Person.setter("addresses", )

Parameters:

  • name (String, Symbol)

    The name of the relation.

  • metadata (Metadata)

    The metadata for the relation.

Returns:

  • (Class)

    The class being set up.

Since:

  • 2.0.0.rc.1



123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/mongoid/relations/accessors.rb', line 123

def setter(name, )
  tap do
    define_method("#{name}=") do |object|
      if relation_exists?(name) || .many? ||
        (object.blank? && send(name))
        set_relation(name, send(name).substitute(object.substitutable))
      else
        build(name, object.substitutable, )
      end
    end
  end
end