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.



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

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.



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

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.



191
192
193
# File 'lib/mongoid/document.rb', line 191

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
106
107
108
109
110
111
112
# File 'lib/mongoid/document.rb', line 103

def paginate(selector = {}, params = {})
  WillPaginate::Collection.create(
    params[:page] || 1,
    params[:per_page] || 20,
    0) do |pager|
      results = collection.find(selector[:conditions], { :limit => pager.per_page, :offset => pager.offset })
      pager.total_entries = results.count
      pager.replace(results.collect { |doc| new(doc) })
  end
end

Instance Method Details

#collectionObject

Get the Mongo::Collection associated with this Document.



117
118
119
# File 'lib/mongoid/document.rb', line 117

def collection
  self.class.collection
end

#destroyObject

Delete this Document from the database.



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

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

#idObject

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



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

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)


140
141
142
# File 'lib/mongoid/document.rb', line 140

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.



153
154
155
156
157
158
159
160
161
162
# File 'lib/mongoid/document.rb', line 153

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



165
166
167
# File 'lib/mongoid/document.rb', line 165

def to_param
  id.to_s
end

#update_attributes(attributes) ⇒ Object

Update the attributes of this Document and return true



170
171
172
# File 'lib/mongoid/document.rb', line 170

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