Method: Mongoid::Document#initialize

Defined in:
lib/mongoid/document.rb

#initialize(attrs = nil, options = nil) ⇒ Document

Instantiate a new Document, setting the Document’s attributes if given. If no attributes are provided, they will be initialized with an empty Hash.

If a primary key is defined, the document’s id will be set to that key, otherwise it will be set to a fresh Moped::BSON::ObjectId string.

Examples:

Create a new document.

Person.new(:title => "Sir")

Parameters:

  • attrs (Hash) (defaults to: nil)

    The attributes to set up the document with.

  • options (Hash) (defaults to: nil)

    A mass-assignment protection options. Supports :as and :without_protection

Returns:

Since:

  • 1.0.0



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/mongoid/document.rb', line 88

def initialize(attrs = nil, options = nil)
  _building do
    @new_record = true
    @attributes ||= {}
    options ||= {}
    apply_pre_processed_defaults
    process_attributes(attrs, options[:as] || :default, !options[:without_protection]) do
      yield(self) if block_given?
    end
    apply_post_processed_defaults
    # @todo: #2586: Need to have access to parent document in these
    #   callbacks.
    run_callbacks(:initialize) unless _initialize_callbacks.empty?
  end
end