Sha256: 207d03a764a7d7f8d174584e2b2daccf488b8f20a85fc8a2a9436ce7790d218e

Contents?: true

Size: 1.61 KB

Versions: 30

Compression:

Stored size: 1.61 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.
    # @param [ Hash ] options The mass assignment scoping options.
    #
    # @return [ Document ] The instantiated document.
    def build(klass, attributes = nil)
      type = (attributes || {})[TYPE]
      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

30 entries across 27 versions & 3 rubygems

Version Path
tdiary-5.0.5 vendor/bundle/gems/tdiary-5.0.4/vendor/bundle/gems/mongoid-6.1.0/lib/mongoid/factory.rb
tdiary-5.0.5 vendor/bundle/gems/mongoid-6.1.0/lib/mongoid/factory.rb
mongoid-5.2.1 lib/mongoid/factory.rb
tdiary-5.0.4 vendor/bundle/gems/mongoid-6.1.0/lib/mongoid/factory.rb
mongoid-6.1.0 lib/mongoid/factory.rb
mongoid-5.2.0 lib/mongoid/factory.rb
mongoid-5.2.0.rc0 lib/mongoid/factory.rb
mongoid-6.1.0.rc0 lib/mongoid/factory.rb
mongoid-6.0.3 lib/mongoid/factory.rb
mongoid-5.1.6 lib/mongoid/factory.rb
mongoid-6.0.2 lib/mongoid/factory.rb
mongoid-6.0.1 lib/mongoid/factory.rb
mongoid-5.1.5 lib/mongoid/factory.rb
mongoid-6.0.0 lib/mongoid/factory.rb
mongoid-5.1.4 lib/mongoid/factory.rb
mongoid-6.0.0.rc0 lib/mongoid/factory.rb
mongoid-6.0.0.beta lib/mongoid/factory.rb
ish_lib_manager-0.0.1 test/dummy/vendor/bundle/ruby/2.3.0/gems/mongoid-5.1.3/lib/mongoid/factory.rb
mongoid-5.1.3 lib/mongoid/factory.rb
mongoid-5.1.2 lib/mongoid/factory.rb