Module: Mongoid::Document

Extended by:
ActiveSupport::Concern
Includes:
Components
Defined in:
lib/mongoid/document.rb,
lib/mongoid/railties/document.rb

Overview

This is the base module for all domain objects that need to be persisted to the database as documents.

Defined Under Namespace

Modules: ClassMethods

Constant Summary

Constants included from Components

Components::MODULES

Constants included from Callbacks

Callbacks::CALLBACKS

Constants included from Copyable

Copyable::COPYABLES

Instance Attribute Summary collapse

Attributes included from State

#destroyed, #flagged_for_destroy

Attributes included from Keys

#identifier

Attributes included from Attributes

#attributes

Instance Method Summary collapse

Methods included from Components

prohibited_methods

Methods included from Callbacks

#run_callbacks

Methods included from Validations

#begin_validate, #exit_validate, #read_attribute_for_validation, #valid?, #validated?

Methods included from Timestamps::Timeless

#timeless, #timestamping?

Methods included from State

#destroyed?, #flagged_for_destroy?, #new_record?, #persisted?, #pushable?, #settable?, #updateable?

Methods included from Sharding

#shard_key_fields, #shard_key_selector

Methods included from Serialization

mongoize, #serializable_hash

Methods included from Safety

merge_safety_options, #safely, #unsafely

Methods included from Reloading

#reload

Methods included from Relations

#embedded?, #embedded_many?, #embedded_one?, #referenced_many?, #referenced_one?, #reload_relations

Methods included from Relations::Synchronization

#remove_inverse_keys, #syncable?, #synced, #synced?, #update_inverse_keys

Methods included from Relations::Reflections

#reflect_on_all_associations, #reflect_on_association

Methods included from Relations::Macros

#associations

Methods included from Relations::Cascading

#cascade!

Methods included from Relations::Accessors

#build, #create_relation, #relation_exists?, #set_relation

Methods included from Persistence

#destroy, #insert, #remove, #save!, #update, #update_attribute, #update_attributes, #update_attributes!, #upsert

Methods included from Persistence::Atomic

#add_to_set, #bit, #inc, #pop, #pull, #pull_all, #push, #push_all, #rename, #set, #unset

Methods included from Matchers

#matches?

Methods included from Keys

#primary_key, #using_object_ids?

Methods included from Inspection

#inspect

Methods included from Fields

#defaults, #fields, option, options

Methods included from Collections

#collection, #db

Methods included from Attributes

#assign_attributes, #attribute_present?, #read_attribute, #remove_attribute, #respond_to?, #write_attribute, #write_attributes

Methods included from Attributes::Processing

#process

Methods included from Dirty

#move_changes, #remove_change, #setters

Methods included from Atomic

#add_atomic_pull, #atomic_delete_modifier, #atomic_insert_modifier, #atomic_path, #atomic_position, #atomic_pulls, #atomic_pushes, #atomic_selector, #atomic_sets, #atomic_unsets, #atomic_updates, #delayed_atomic_pulls, #delayed_atomic_sets

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Mongoid::Attributes

Instance Attribute Details

#new_recordObject (readonly)

Returns the value of attribute new_record.



10
11
12
# File 'lib/mongoid/document.rb', line 10

def new_record
  @new_record
end

Instance Method Details

#<=>(other) ⇒ Integer

Default comparison is via the string version of the id.

Examples:

Compare two documents.

person <=> other_person

Parameters:

  • other (Document)

    The document to compare with.

Returns:



20
21
22
# File 'lib/mongoid/document.rb', line 20

def <=>(other)
  attributes["_id"].to_s <=> other.attributes["_id"].to_s
end

#==(other) ⇒ true, false

Performs equality checking on the document ids. For more robust equality checking please override this method.

Examples:

Compare for equality.

document == other

Parameters:

Returns:

  • (true, false)

    True if the ids are equal, false if not.



33
34
35
36
# File 'lib/mongoid/document.rb', line 33

def ==(other)
  self.class == other.class &&
    attributes["_id"] == other.attributes["_id"]
end

#===(other) ⇒ true, false

Performs class equality checking.

Examples:

Compare the classes.

document === other

Parameters:

Returns:

  • (true, false)

    True if the classes are equal, false if not.



46
47
48
# File 'lib/mongoid/document.rb', line 46

def ===(other)
  other.is_a?(self.class)
end

#_destroyObject

Used in conjunction with fields_for to build a form element for the destruction of this association. Always returns false because Mongoid only supports immediate deletion of associations.

See ActionView::Helpers::FormHelper::fields_for for more info.



8
9
10
# File 'lib/mongoid/railties/document.rb', line 8

def _destroy
  false
end

#as_documentHash

Return a hash of the entire document hierarchy from this document and below. Used when the attributes are needed for everything and not just the current document.

Examples:

Get the full hierarchy.

person.as_document

Returns:

  • (Hash)

    A hash of all attributes in the hierarchy.



158
159
160
161
162
163
164
165
166
167
# File 'lib/mongoid/document.rb', line 158

def as_document
  attributes.tap do |attrs|
    relations.each_pair do |name, meta|
      if meta.embedded?
        relation = send(name)
        attrs[name] = relation.as_document unless relation.blank?
      end
    end
  end
end

#becomes(klass) ⇒ Document

Returns an instance of the specified class with the attributes and errors of the current document.

Examples:

Return a subclass document as a superclass instance.

manager.becomes(Person)

Parameters:

  • klass (Class)

    The class to become.

Returns:

  • (Document)

    An instance of the specified class.

Raises:

  • (ArgumentError)

    If the class doesn’t include Mongoid::Document



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/mongoid/document.rb', line 180

def becomes(klass)
  unless klass.include?(Mongoid::Document)
    raise ArgumentError, "A class which includes Mongoid::Document is expected"
  end
  klass.instantiate(frozen? ? attributes.dup : attributes).tap do |became|
    became.instance_variable_set(:@errors, errors)
    became.instance_variable_set(:@new_record, new_record?)
    became.instance_variable_set(:@destroyed, destroyed?)
    became._type = klass.to_s
  end
end

#eql?(other) ⇒ true, false

Delegates to ==. Used when needing checks in hashes.

Examples:

Perform equality checking.

document.eql?(other)

Parameters:

Returns:

  • (true, false)

    True if equal, false if not.



58
59
60
# File 'lib/mongoid/document.rb', line 58

def eql?(other)
  self == (other)
end

#freezeDocument

Freezes the internal attributes of the document.

Examples:

Freeze the document

document.freeze

Returns:

Since:

  • 2.0.0



70
71
72
73
# File 'lib/mongoid/document.rb', line 70

def freeze
  attributes.freeze
  self
end

#frozen?true, false

Checks if the document is frozen

Examples:

Check if frozen

document.frozen?

Returns:

  • (true, false)

    True if frozen, else false.

Since:

  • 2.0.0



83
84
85
# File 'lib/mongoid/document.rb', line 83

def frozen?
  raw_attributes.frozen?
end

#hashInteger

Delegates to id in order to allow two records of the same type and id to work with something like:

[ Person.find(1), Person.find(2), Person.find(3) ] &
[ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]

Examples:

Get the hash.

document.hash

Returns:

  • (Integer)

    The hash of the document’s id.



97
98
99
# File 'lib/mongoid/document.rb', line 97

def hash
  raw_attributes["_id"].hash
end

#identifyBSON::ObjectId, String

Generate an id for this Document.

Examples:

Create the id.

person.identify

Returns:



107
108
109
# File 'lib/mongoid/document.rb', line 107

def identify
  Identity.new(self).create
end

#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 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:



126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/mongoid/document.rb', line 126

def initialize(attrs = nil, options = nil)
  _building do
    @new_record = true
    @attributes ||= {}
    options ||= {}
    process(attrs, options[:as] || :default, !options[:without_protection]) do
      identify
      apply_defaults
      yield(self) if block_given?
    end
    run_callbacks(:initialize) { self }
  end
end

#to_aArray<Document>

Return an array with this Document only in it.

Examples:

Return the document in an array.

document.to_a

Returns:

  • (Array<Document>)

    An array with the document as its only item.



146
147
148
# File 'lib/mongoid/document.rb', line 146

def to_a
  [ self ]
end