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

- (Document) build(klass, attributes = nil)

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: nil)

    The document attributes.

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

- (Document) from_db(klass, attributes = nil, selected_fields = nil)

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: nil)

    The document attributes.

  • selected_fields (Array) (defaults to: nil)

    If instantiated from a criteria using #only we give the document a list of the selected fields.

Returns:

  • (Document)

    The instantiated document.



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

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