Module: Mongoid::Factory

Extended by:
Factory
Included in:
Factory
Defined in:
lib/mongoid/factory.rb

Overview

Instantiates documents that came from the database.

Instance Method Summary collapse

Instance Method Details

#build(klass, attributes = {}) ⇒ Document

Builds a new Document from the supplied attributes.

Examples:

Build the document.

Mongoid::Factory.build(Person, { "name" => "Durran" })

Parameters:

  • klass (Class)

    The class to instantiate from if _type is not present.

  • attributes (Hash) (defaults to: {})

    The document attributes.

Returns:

  • (Document)

    The instantiated document.



17
18
19
20
# File 'lib/mongoid/factory.rb', line 17

def build(klass, attributes = {})
  type = (attributes || {})["_type"]
  type.blank? ? klass.new(attributes) : type.constantize.new(attributes)
end

#from_db(klass, attributes = {}) ⇒ Document

Builds a new Document from the supplied attributes loaded from the database.

Examples:

Build the document.

Mongoid::Factory.from_db(Person, { "name" => "Durran" })

Parameters:

  • klass (Class)

    The class to instantiate from if _type is not present.

  • attributes (Hash) (defaults to: {})

    The document attributes.

Returns:

  • (Document)

    The instantiated document.



32
33
34
35
# File 'lib/mongoid/factory.rb', line 32

def from_db(klass, attributes = {})
  type = attributes["_type"]
  type.blank? ? klass.instantiate(attributes) : type.constantize.instantiate(attributes)
end