Module: Mongoid::Factory

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

Overview

Instantiates documents that came from the database.

Constant Summary collapse

TYPE =
"_type".freeze

Instance Method Summary collapse

Instance Method Details

#build(klass, attributes = nil) ⇒ 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: nil)

    The document attributes.

Returns:

  • (Document)

    The instantiated document.



19
20
21
22
23
24
25
26
27
# File 'build/mongoid-7.0/lib/mongoid/factory.rb', line 19

def build(klass, attributes = nil)
  attributes ||= {}
  type = attributes[TYPE] || attributes[TYPE.to_sym]
  if type && klass._types.include?(type)
    type.constantize.new(attributes)
  else
    klass.new(attributes)
  end
end

#from_db(klass, attributes = nil, criteria = nil) ⇒ 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: nil)

    The document attributes.

  • selected_fields (Array)

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

Returns:

  • (Document)

    The instantiated document.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'build/mongoid-7.0/lib/mongoid/factory.rb', line 41

def from_db(klass, attributes = nil, criteria = nil)
  selected_fields = criteria.options[:fields] if criteria
  type = (attributes || {})[TYPE]
  if type.blank?
    obj = klass.instantiate(attributes, selected_fields)
    if criteria && criteria.association && criteria.parent_document
      obj.set_relation(criteria.association.inverse, criteria.parent_document)
    end
    obj
  else
    camelized = type.camelize
    begin
      camelized.constantize.instantiate(attributes, selected_fields)
    rescue NameError
      raise Errors::UnknownModel.new(camelized, type)
    end
  end
end