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 = {}, options = {}) ⇒ 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.

  • optiosn (Hash)

    The mass assignment scoping options.

Returns:

  • (Document)

    The instantiated document.



18
19
20
21
22
23
24
25
# File 'lib/mongoid/factory.rb', line 18

def build(klass, attributes = {}, options = {})
  type = (attributes || {})["_type"]
  if type && klass._types.include?(type)
    type.constantize.new(attributes, options)
  else
    klass.new(attributes, options)
  end
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.



37
38
39
40
41
42
43
44
# File 'lib/mongoid/factory.rb', line 37

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