Sha256: ab0fdbaec1ba64da3a4478d09d177cc8e58a76516736bc8e1b18dfbdf2645d3b

Contents?: true

Size: 1.44 KB

Versions: 57

Compression:

Stored size: 1.44 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.
    # @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

57 entries across 57 versions & 2 rubygems

Version Path
classiccms-0.7.5 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.7.4 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.7.3 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
mongoid-2.8.1 lib/mongoid/factory.rb
mongoid-2.8.0 lib/mongoid/factory.rb
classiccms-0.7.2 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.7.1 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.7.0 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
mongoid-2.7.1 lib/mongoid/factory.rb
mongoid-2.7.0 lib/mongoid/factory.rb
mongoid-2.6.0 lib/mongoid/factory.rb
mongoid-2.5.2 lib/mongoid/factory.rb
classiccms-0.6.9 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.6.8 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.6.7 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
mongoid-2.5.1 lib/mongoid/factory.rb
classiccms-0.6.6 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.6.5 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.6.4 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb
classiccms-0.6.3 vendor/bundle/gems/mongoid-2.4.10/lib/mongoid/factory.rb