Class: Mongoid::Document

Inherits:
Object show all
Includes:
ActiveSupport::Callbacks, Validatable
Defined in:
lib/mongoid/document.rb

Overview

:nodoc:

Constant Summary collapse

AGGREGATE_REDUCE =
"function(obj, prev) { prev.count++; }"
GROUP_BY_REDUCE =
"function(obj, prev) { prev.group.push(obj); }"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Document

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



127
128
129
130
# File 'lib/mongoid/document.rb', line 127

def initialize(attributes = {})
  @attributes = attributes.symbolize_keys if attributes
  @attributes = {} unless attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



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

def attributes
  @attributes
end

#parentObject

Returns the value of attribute parent.



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

def parent
  @parent
end

Class Method Details

.add_association(type, class_name, name) ⇒ Object

Adds the association to the associations hash with the type as the key, then adds the accessors for the association.



173
174
175
176
177
178
179
180
# File 'lib/mongoid/document.rb', line 173

def add_association(type, class_name, name)
  define_method(name) do
    Mongoid::Associations::AssociationFactory.create(type, name, self)
  end
  define_method("#{name}=") do |object|
    @attributes[name] = object.mongoidize
  end
end

.aggregate(fields, selector) ⇒ Object

Get an aggregate count for the supplied group of fields and the selector that is provided.



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

def aggregate(fields, selector)
  collection.group(fields, selector, { :count => 0 }, AGGREGATE_REDUCE)
end

.belongs_to(association_name) ⇒ Object

Create an association to a parent Document.



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

def belongs_to(association_name)
  add_association(:belongs_to, association_name.to_s.classify, association_name)
end

.collectionObject

Get the Mongo::Collection associated with this Document.



31
32
33
34
# File 'lib/mongoid/document.rb', line 31

def collection
  @collection_name = self.to_s.demodulize.tableize
  @collection ||= Mongoid.database.collection(@collection_name)
end

.create(attributes = {}) ⇒ Object

Create a new Document with the supplied attribtues, and insert it into the database.



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

def create(attributes = {})
  new(attributes).save
end

.fields(*names) ⇒ Object

Defines all the fields that are accessable on the Document For each field that is defined, a getter and setter will be added as an instance method to the Document.



44
45
46
47
48
49
50
51
# File 'lib/mongoid/document.rb', line 44

def fields(*names)
  @fields = []
  names.flatten.each do |name|
    @fields << name
    define_method(name) { read_attribute(name) }
    define_method("#{name}=") { |value| write_attribute(name, value) }
  end
end

.find(*args) ⇒ Object

Find all Documents in several ways. Model.find(:first, :attribute => “value”) Model.find(:all, :attribute => “value”)



56
57
58
59
60
61
62
63
# File 'lib/mongoid/document.rb', line 56

def find(*args)
  type, selector = args[0], args[1]
  case type
  when :all then find_all(selector[:conditions])
  when :first then find_first(selector[:conditions])
  else find_first(Mongo::ObjectID.from_string(type.to_s))
  end
end

.find_all(selector = nil) ⇒ Object

Find all Documents given the passed selector, which is a Hash of attributes that must match the Document in the database exactly.



73
74
75
# File 'lib/mongoid/document.rb', line 73

def find_all(selector = nil)
  collection.find(selector).collect { |doc| new(doc) }
end

.find_first(selector = nil) ⇒ Object

Find a single Document given the passed selector, which is a Hash of attributes that must match the Document in the database exactly.



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

def find_first(selector = nil)
  new(collection.find_one(selector))
end

.group!(docs) ⇒ Object

Takes the supplied raw grouping of documents and alters it to a grouping of actual document objects.



184
185
186
# File 'lib/mongoid/document.rb', line 184

def group!(docs)
  docs["group"] = docs["group"].collect { |attrs| new(attrs) }; docs
end

.group_by(fields, selector) ⇒ Object

Find all Documents given the supplied criteria, grouped by the fields provided.



79
80
81
82
83
# File 'lib/mongoid/document.rb', line 79

def group_by(fields, selector)
  collection.group(fields, selector, { :group => [] }, GROUP_BY_REDUCE).collect do |docs|
    group!(docs)
  end
end

.has_many(association_name) ⇒ Object

Create a one-to-many association between Documents.



86
87
88
# File 'lib/mongoid/document.rb', line 86

def has_many(association_name)
  add_association(:has_many, association_name.to_s.classify, association_name)
end

.has_one(association_name) ⇒ Object

Create a one-to-many association between Documents.



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

def has_one(association_name)
  add_association(:has_one, association_name.to_s.titleize, association_name)
end

.index(name, options = { :unique => false }) ⇒ Object

Adds an index on the field specified. Options can be :unique => true or :unique => false. It will default to the latter.



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

def index(name, options = { :unique => false })
  collection.create_index(name, options)
end

.paginate(selector = {}, params = {}) ⇒ Object

Find all documents in paginated fashion given the supplied arguments. If no parameters are passed just default to offset 0 and limit 20.



103
104
105
# File 'lib/mongoid/document.rb', line 103

def paginate(selector = {}, params = {})
  collection.find(selector[:conditions], Mongoid::Paginator.new(params).options).collect { |doc| new(doc) }
end

Instance Method Details

#collectionObject

Get the Mongo::Collection associated with this Document.



110
111
112
# File 'lib/mongoid/document.rb', line 110

def collection
  self.class.collection
end

#destroyObject

Delete this Document from the database.



115
116
117
# File 'lib/mongoid/document.rb', line 115

def destroy
  collection.remove(:_id => id)
end

#idObject

Get the Mongo::ObjectID associated with this object. This is in essence the primary key.



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

def id
  @attributes[:_id]
end

#new_record?Boolean

Returns true is the Document has not been persisted to the database, false if it has.

Returns:

  • (Boolean)


133
134
135
# File 'lib/mongoid/document.rb', line 133

def new_record?
  @attributes[:_id].nil?
end

#saveObject

Save this document to the database. If this document is the root document in the object graph, it will save itself, and return self. If the document is embedded within another document, or is multiple levels down the tree, the root object will get saved, and return itself.



146
147
148
149
150
151
152
153
154
155
# File 'lib/mongoid/document.rb', line 146

def save
  if @parent
    @parent.save
  else
    run_callbacks(:before_save)
    collection.save(@attributes)
    run_callbacks(:after_save)
    return self
  end
end

#to_paramObject

Returns the id of the Document



158
159
160
# File 'lib/mongoid/document.rb', line 158

def to_param
  id.to_s
end

#update_attributes(attributes) ⇒ Object

Update the attributes of this Document and return true



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

def update_attributes(attributes)
  @attributes = attributes.symbolize_keys!; save; true
end