Sha256: cd7aebbefa857f79de826248f8c306d761dff8a3a5168bc879956146d99584f6

Contents?: true

Size: 1.43 KB

Versions: 7

Compression:

Stored size: 1.43 KB

Contents

# 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)
      type = (attributes || {})["_type"]
      if type.blank?
        klass.instantiate(attributes)
      else
        type.camelize.constantize.instantiate(attributes)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
mongoid-3.0.5 lib/mongoid/factory.rb
mongoid-3.0.4 lib/mongoid/factory.rb
mongoid-3.0.3 lib/mongoid/factory.rb
mongoid-3.0.2 lib/mongoid/factory.rb
mongoid-3.0.1 lib/mongoid/factory.rb
mongoid-3.0.0 lib/mongoid/factory.rb
mongoid-3.0.0.rc lib/mongoid/factory.rb