Sha256: 1602cc54fd4af2082df70df33e5d67877fc95036796eb64e207c972b06fde5fb

Contents?: true

Size: 1.25 KB

Versions: 17

Compression:

Stored size: 1.25 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:

  # 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.
    #
    # @return [ Document ] The instantiated document.
    def build(klass, attributes = {})
      type = (attributes || {})["_type"]
      (type && klass._types.include?(type)) ? type.constantize.new(attributes) : klass.new(attributes)
    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 = {})
      type = attributes["_type"]
      type.blank? ? klass.instantiate(attributes) : type.constantize.instantiate(attributes)
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
mongoid-2.2.6 lib/mongoid/factory.rb
mongoid-2.2.5 lib/mongoid/factory.rb
mongoid-2.2.4 lib/mongoid/factory.rb
mongoid-2.2.3 lib/mongoid/factory.rb
mongoid-2.2.2 lib/mongoid/factory.rb
mongoid-2.2.1 lib/mongoid/factory.rb
mongoid-2.2.0 lib/mongoid/factory.rb
mongoid-2.1.9 lib/mongoid/factory.rb
mongoid-2.1.8 lib/mongoid/factory.rb
mongoid-2.1.7 lib/mongoid/factory.rb
mongoid-2.1.6 lib/mongoid/factory.rb
mongoid-2.1.5 lib/mongoid/factory.rb
mongoid-2.1.4 lib/mongoid/factory.rb
mongoid-2.1.3 lib/mongoid/factory.rb
mongoid-2.1.2 lib/mongoid/factory.rb
mongoid-2.1.1 lib/mongoid/factory.rb
mongoid-2.1.0 lib/mongoid/factory.rb