Module: Mongoid::Factory
Overview
Instantiates documents that came from the database.
Constant Summary collapse
- TYPE =
Deprecated.
"_type".freeze
Instance Method Summary collapse
-
#build(klass, attributes = nil) ⇒ Document
Builds a new
Document
from the supplied attributes. -
#from_db(klass, attributes = nil, criteria = nil, selected_fields = nil) ⇒ Document
Builds a new
Document
from the supplied attributes loaded from the database.
Instance Method Details
#build(klass, attributes = nil) ⇒ Document
Builds a new Document
from the supplied attributes.
This method either instantiats klass or a descendant of klass if the attributes include klass’ discriminator key.
If the attributes contain the discriminator key (which is _type by default) and the discriminator value does not correspond to a descendant of klass then this method would create an instance of klass.
29 30 31 32 33 34 35 36 37 38 |
# File 'lib/mongoid/factory.rb', line 29 def build(klass, attributes = nil) attributes ||= {} dvalue = attributes[klass.discriminator_key] || attributes[klass.discriminator_key.to_sym] type = klass.get_discriminator_mapping(dvalue) if type type.new(attributes) else klass.new(attributes) end end |
#from_db(klass, attributes = nil, criteria = nil, selected_fields = nil) ⇒ Document
Builds a new Document
from the supplied attributes loaded from the database.
If the attributes contain the discriminator key (which is _type by default) and the discriminator value does not correspond to a descendant of klass then this method raises an UnknownModel error.
If a criteria object is given, it is used in two ways:
-
If the criteria has a list of fields specified via #only, only those fields are populated in the returned document.
-
If the criteria has a referencing association (i.e., this document is being instantiated as an association of another document), the other document is also populated in the returned document’s reverse association, if one exists.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/mongoid/factory.rb', line 66 def from_db(klass, attributes = nil, criteria = nil, selected_fields = nil) if criteria selected_fields ||= criteria.[:fields] end type = (attributes || {})[klass.discriminator_key] 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 constantized = klass.get_discriminator_mapping(type) unless constantized camelized = type.camelize # Check if the class exists begin constantized = camelized.constantize rescue NameError raise Errors::UnknownModel.new(camelized, type) end end # Check if the class is a Document class if !constantized.respond_to?(:instantiate) raise Errors::UnknownModel.new(camelized, type) end constantized.instantiate(attributes, selected_fields) end end |