Class: Mongoid::Document

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

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

Methods included from Commands

included

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.



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

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

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



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

def attributes
  @attributes
end

#parentObject

Returns the value of attribute parent.



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

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.



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

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

.aggregate(fields, params = {}) ⇒ Object

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



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

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

.all(*args) ⇒ Object

Find all Documents 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 all(*args)
  find(:all, *args)
end

.belongs_to(association_name) ⇒ Object

Adds the association back to the parent document.



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

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.



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

def collection
  @collection_name = self.to_s.demodulize.tableize
  @collection ||= Mongoid.database.collection(@collection_name)
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.



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

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”)



55
56
57
# File 'lib/mongoid/document.rb', line 55

def find(*args)
  Criteria.translate(*args).execute(self)
end

.first(*args) ⇒ Object

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



61
62
63
# File 'lib/mongoid/document.rb', line 61

def first(*args)
  find(:first, *args)
end

.group_by(fields, params = {}) ⇒ Object

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



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

def group_by(fields, params = {})
  selector = params[:condition]
  collection.group(fields, selector, { :group => [] }, GROUP_BY_REDUCE).collect do |docs|
    docs["group"] = docs["group"].collect { |attrs| new(attrs) }; docs
  end
end

.has_many(association_name) ⇒ Object

Create a one-to-many association between Documents.



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

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.



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

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

.has_timestampsObject

Adds timestamps on the Document in the form of the fields ‘created_on’ and ‘last_modified’



92
93
94
95
96
97
98
99
100
# File 'lib/mongoid/document.rb', line 92

def has_timestamps
  fields :created_at, :last_modified
  class_eval do
    before_create \
      :update_created_at,
      :update_last_modified
    before_save :update_last_modified
  end
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.



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

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

.paginate(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.



110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/mongoid/document.rb', line 110

def paginate(params = {})
  selector = params[:conditions]
  WillPaginate::Collection.create(
    params[:page] || 1,
    params[:per_page] || 20,
    0) do |pager|
      results = collection.find(selector, { :sort => params[:sort],
                                            :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.



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

def collection
  self.class.collection
end

#idObject

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



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

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)


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

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

#to_paramObject

Returns the id of the Document



150
151
152
# File 'lib/mongoid/document.rb', line 150

def to_param
  id.to_s
end