Module: Mongoid::Document::ClassMethods

Defined in:
lib/mongoid/document.rb

Instance Method Summary collapse

Instance Method Details

#_typesObject

Returns all types to query for when using this class as the base.



99
100
101
# File 'lib/mongoid/document.rb', line 99

def _types
  @_type ||= (self.subclasses + [ self.name ])
end

#collectionObject

Returns the collection associated with this Document. If the document is embedded, there will be no collection associated with it.

Returns: Mongo::Collection



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

def collection
  raise Errors::InvalidCollection.new(self) if embedded
  self._collection ||= Mongoid::Collection.new(self, self.collection_name)
  add_indexes; self._collection
end

#dbObject

Return the database associated with this class.



25
26
27
# File 'lib/mongoid/document.rb', line 25

def db
  collection.db
end

#human_nameObject

Returns a human readable version of the class.

Example:

MixedDrink.human_name # returns "Mixed Drink"



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

def human_name
  name.labelize
end

#inherited(subclass) ⇒ Object

Perform default behavior but mark the hierarchy as being hereditary.



41
42
43
44
# File 'lib/mongoid/document.rb', line 41

def inherited(subclass)
  super(subclass)
  self.hereditary = true
end

#instantiate(attrs = nil, allocating = false) ⇒ Object

Instantiate a new object, only when loaded from the database or when the attributes have already been typecast.

Example:

Person.instantiate(:title => "Sir", :age => 30)



61
62
63
64
65
66
67
68
69
70
# File 'lib/mongoid/document.rb', line 61

def instantiate(attrs = nil, allocating = false)
  attributes = attrs || {}
  if attributes["_id"] || allocating
    document = allocate
    document.instance_variable_set(:@attributes, attributes)
    return document
  else
    return new(attrs)
  end
end

#key(*fields) ⇒ Object

Defines the field that will be used for the id of this Document. This set the id of this Document before save to a parameterized version of the field that was supplied. This is good for use for readable URLS in web applications.

Example:

class Person
  include Mongoid::Document
  key :first_name, :last_name
end


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

def key(*fields)
  self.primary_key = fields
  before_save :identify
end

#store_in(name) ⇒ Object

Macro for setting the collection name to store in.

Example:

Person.store_in :populdation



93
94
95
96
# File 'lib/mongoid/document.rb', line 93

def store_in(name)
  self.collection_name = name.to_s
  self._collection = Mongoid::Collection.new(self, name.to_s)
end