module Mongoid::Relations::Builders::ClassMethods

Public Instance Methods

builder(name, metadata) click to toggle source

Defines a builder method for an embeds_one relation. This is defined as build_name.

@example

Person.builder("name")

@param [ String, Symbol ] name The name of the relation.

@return [ Class ] The class being set up.

@since 2.0.0.rc.1

# File lib/mongoid/relations/builders.rb, line 64
def builder(name, metadata)
  re_define_method("build_#{name}") do |*args|
    attributes, options = parse_args(*args)
    document = Factory.build(metadata.klass, attributes, options)
    _building do
      child = send("#{name}=", document)
      child.run_callbacks(:build)
      child
    end
  end
  self
end
creator(name, metadata) click to toggle source

Defines a creator method for an embeds_one relation. This is defined as create_name. After the object is built it will immediately save.

@example

Person.creator("name")

@param [ String, Symbol ] name The name of the relation.

@return [ Class ] The class being set up.

@since 2.0.0.rc.1

# File lib/mongoid/relations/builders.rb, line 89
def creator(name, metadata)
  re_define_method("create_#{name}") do |*args|
    attributes, options = parse_args(*args)
    document = Factory.build(metadata.klass, attributes, options)
    doc = send("#{name}=", document)
    doc.save
    save if new_record? && metadata.stores_foreign_key?
    doc
  end
  self
end