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



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

def getter(name, )
  tap do
    define_method(name) do |*args|
      reload, variable = args.first, "@#{name}"
      options = options(args)
      if instance_variable_defined?(variable) && !reload
        instance_variable_get(variable)
      else
        build(
          name,
          @attributes[.key],
          ,
          options.merge(:binding => true, :eager => .embedded?)
        )
      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



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/mongoid/relations/accessors.rb', line 155

def setter(name, )
  tap do
    define_method("#{name}=") do |*args|
      object, options = args.first, options(args)
      variable = "@#{name}"
      if relation_exists?(name) && !object.is_a?(Hash)
        substitute(name, object, options)
      else
        if .embedded? && object.blank? && send(name)
          substitute(name, object, options)
        else
          build(name, object, , options.merge(:eager => true))
        end
      end
    end
  end
end