Sha256: 23d1a7e78c841b6100901799574be3db3ef5771fabb95b77e5769f7b6a08798d
Contents?: true
Size: 1.59 KB
Versions: 9
Compression:
Stored size: 1.59 KB
Contents
# encoding: utf-8 module Mongoid # Instantiates documents that came from the database. module Factory extend self TYPE = "_type".freeze # Builds a new +Document+ from the supplied attributes. # # @example Build the document. # Mongoid::Factory.build(Person, { "name" => "Durran" }) # # @param [ Class ] klass The class to instantiate from if _type is not present. # @param [ Hash ] attributes The document attributes. # # @return [ Document ] The instantiated document. 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 # Builds a new +Document+ from the supplied attributes loaded from the # database. # # @example Build the document. # Mongoid::Factory.from_db(Person, { "name" => "Durran" }) # # @param [ Class ] klass The class to instantiate from if _type is not present. # @param [ Hash ] attributes The document attributes. # @param [ Array ] selected_fields If instantiated from a criteria using # #only we give the document a list of the selected fields. # # @return [ Document ] The instantiated document. 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 end end
Version data entries
9 entries across 9 versions & 2 rubygems