Module: Mongoid::Relations::Builders::ClassMethods

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

Overview

Since:

  • 2.0.0.rc.1

Instance Method Summary collapse

Instance Method Details

#builder(name, metadata) ⇒ Class

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

Examples:

Person.builder("name")

Parameters:

  • name (String, Symbol)

    The name of the relation.

Returns:

  • (Class)

    The class being set up.

Since:

  • 2.0.0.rc.1



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/mongoid/relations/builders.rb', line 65

def builder(name, )
  re_define_method("build_#{name}") do |*args|
    attributes, options = parse_args(*args)
    document = Factory.build(.klass, attributes, options)
    _building do
      child = send("#{name}=", document)
      child.run_callbacks(:build)
      child
    end
  end
  self
end

#creator(name, metadata) ⇒ Class

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

Examples:

Person.creator("name")

Parameters:

  • name (String, Symbol)

    The name of the relation.

Returns:

  • (Class)

    The class being set up.

Since:

  • 2.0.0.rc.1



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/mongoid/relations/builders.rb', line 90

def creator(name, )
  re_define_method("create_#{name}") do |*args|
    attributes, options = parse_args(*args)
    document = Factory.build(.klass, attributes, options)
    doc = send("#{name}=", document)
    doc.save
    save if new_record? && .stores_foreign_key?
    doc
  end
  self
end