Skip to content
This repository
tree: 9aa7e29758
Fetching contributors…

Cannot retrieve contributors at this time

file 46 lines (43 sloc) 1.536 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
# encoding: utf-8
module Mongoid

  # Instantiates documents that came from the database.
  module Factory
    extend self

    # 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.
    # @param [ Hash ] optiosn The mass assignment scoping options.
    #
    # @return [ Document ] The instantiated document.
    def build(klass, attributes = nil, options = {})
      type = (attributes || {})["_type"]
      if type && klass._types.include?(type)
        type.constantize.new(attributes, options)
      else
        klass.new(attributes, options)
      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.
    #
    # @return [ Document ] The instantiated document.
    def from_db(klass, attributes = nil, criteria_instance_id = nil)
      type = (attributes || {})["_type"]
      if type.blank?
        klass.instantiate(attributes, criteria_instance_id)
      else
        type.camelize.constantize.instantiate(attributes, criteria_instance_id)
      end
    end
  end
end
Something went wrong with that request. Please try again.