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 Atomic

Atomic::UPDATES

Instance Attribute Summary collapse

Attributes included from State

#destroyed, #flagged_for_destroy

Attributes included from Relations

#metadata

Attributes included from Attributes

#attributes

Instance Method Summary collapse

Methods included from Components

prohibited_methods

Methods included from Copyable

#clone

Methods included from Callbacks

#run_after_callbacks, #run_before_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

#serializable_hash

Methods included from Sessions

clear, #collection, #collection_name, default, #mongo_session, #with, with_name

Methods included from Reloading

#reload

Methods included from Relations

#embedded?, #embedded_many?, #embedded_one?, #metadata_name, #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::AutoSave

#autosaved?, #begin_autosave, #exit_autosave

Methods included from Relations::Accessors

#__build__, #create_relation, #relation_exists?, #set_relation

Methods included from Persistence

#destroy, #insert, #remove, #save, #save!, #touch, #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 Inspection

#inspect

Methods included from Hierarchy

#_children, #_root, #collect_children, #hereditary?, #parentize, #remove_child, #reset_persisted_children

Methods included from Fields

#apply_default, #apply_defaults, #apply_post_processed_defaults, #apply_pre_processed_defaults, #attribute_names, option, options, #using_object_ids?

Methods included from Evolvable

#__evolve_object_id__

Methods included from Attributes

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

Methods included from Attributes::Readonly

#attribute_writable?

Methods included from Attributes::Processing

#process_attributes

Methods included from Dirty

#changed, #changed?, #changed_attributes, #changes, #children_changed?, #move_changes, #post_persist, #previous_changes, #remove_change, #setters

Methods included from Atomic

#add_atomic_pull, #add_atomic_unset, #atomic_array_add_to_sets, #atomic_array_pulls, #atomic_array_pushes, #atomic_attribute_name, #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, #delayed_atomic_unsets, #flag_as_destroyed

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:

  • (Integer)

    -1, 0, 1.

Since:

  • 1.0.0



22
23
24
# File 'lib/mongoid/document.rb', line 22

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:

  • other (Document, Object)

    The other object to compare with.

Returns:

  • (true, false)

    True if the ids are equal, false if not.

Since:

  • 1.0.0



37
38
39
40
# File 'lib/mongoid/document.rb', line 37

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:

  • other (Document, Object)

    The other object to compare with.

Returns:

  • (true, false)

    True if the classes are equal, false if not.

Since:

  • 1.0.0



52
53
54
# File 'lib/mongoid/document.rb', line 52

def ===(other)
  other.class == Class ? self.class === other : self == other
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.

Since:

  • 1.0.0



189
190
191
192
193
194
195
196
197
198
# File 'lib/mongoid/document.rb', line 189

def as_document
  return attributes if frozen?
  embedded_relations.each_pair do |name, meta|
    without_autobuild do
      relation = send(name)
      attributes[meta.store_as] = relation.as_document unless relation.blank?
    end
  end
  attributes
end

#becomes(klass) ⇒ Document

Returns an instance of the specified class with the attributes, errors, and embedded documents 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

Since:

  • 2.0.0



213
214
215
216
217
218
219
220
221
222
223
# File 'lib/mongoid/document.rb', line 213

def becomes(klass)
  unless klass.include?(Mongoid::Document)
    raise ArgumentError, "A class which includes Mongoid::Document is expected"
  end
  became = klass.instantiate(as_document.__deep_copy__)
  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
  became
end

#cache_keyString

Print out the cache key. This will append different values on the plural model name.

If new_record? - will append /new If not - will append /id-updated_at.to_s(:number) Without updated_at - will append /id

This is usually called insode a cache() block

Examples:

Returns the cache key

document.cache_key

Returns:

  • (String)

    the string with or without updated_at

Since:

  • 2.4.0



240
241
242
243
244
# File 'lib/mongoid/document.rb', line 240

def cache_key
  return "#{model_key}/new" if new_record?
  return "#{model_key}/#{id}-#{updated_at.utc.to_s(:number)}" if updated_at
  "#{model_key}/#{id}"
end

#eql?(other) ⇒ true, false

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

Examples:

Perform equality checking.

document.eql?(other)

Parameters:

  • other (Document, Object)

    The object to check against.

Returns:

  • (true, false)

    True if equal, false if not.

Since:

  • 1.0.0



66
67
68
# File 'lib/mongoid/document.rb', line 66

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



78
79
80
# File 'lib/mongoid/document.rb', line 78

def freeze
  as_document.freeze and 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



90
91
92
# File 'lib/mongoid/document.rb', line 90

def frozen?
  attributes.frozen?
end

#hashInteger

Delegates to identity in order to allow two records of the same identity 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 identity.

Since:

  • 1.0.0



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

def hash
  identity.hash
end

#identityArray

A Document’s is identified absolutely by it’s class and database id:

Person.first.identity #=> [Person, Moped::BSON::ObjectId(‘4f775130a04745933a000003’)]

Examples:

Get the identity

document.identity

Returns:

  • (Array)

    An array containing [document.class, document.id]

Since:

  • 3.0.0



120
121
122
# File 'lib/mongoid/document.rb', line 120

def identity
  [ self.class, self.id ]
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 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



141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/mongoid/document.rb', line 141

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
    run_callbacks(:initialize) unless _initialize_callbacks.empty?
  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.

Since:

  • 1.0.0



175
176
177
# File 'lib/mongoid/document.rb', line 175

def to_a
  [ self ]
end

#to_keyObject

Return the key value for the document.

Examples:

Return the key.

document.to_key

Returns:

  • (Object)

    The id of the document or nil if new.

Since:

  • 2.4.0



163
164
165
# File 'lib/mongoid/document.rb', line 163

def to_key
  (persisted? || destroyed?) ? [ id ] : nil
end