Sha256: 52e23ebae36d4f3f7af761aa199feb2581d1835ae5747eb278062faa8ef55ebc

Contents?: true

Size: 1.23 KB

Versions: 2

Compression:

Stored size: 1.23 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.blank? ? klass.new(attributes) : type.constantize.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

2 entries across 2 versions & 2 rubygems

Version Path
mongoid-braxton-2.0.2 lib/mongoid/factory.rb
mongoid-2.0.2 lib/mongoid/factory.rb