Module: MongoMapper::Document::ClassMethods

Defined in:
lib/mongo_mapper/document.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object (protected)



320
321
322
323
324
325
326
327
328
329
# File 'lib/mongo_mapper/document.rb', line 320

def method_missing(method, *args)
  finder = DynamicFinder.new(method)

  if finder.found?
    meta_def(finder.method) { |*args| dynamic_find(finder, args) }
    send(finder.method, *args)
  else
    super
  end
end

Instance Method Details

#all(options = {}) ⇒ Array

Returns all documents in your collection that match the provided conditions.

Parameters:

  • options (Hash) (defaults to: {})

    any conditions understood by FinderOptions.to_mongo_criteria

Returns:

  • (Array)

    all documents in your collection that match the provided conditions

See Also:



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

def all(options={})
  find_every(options)
end

#collectionObject

Returns the Mongo Ruby driver collection object.

Returns:

  • the Mongo Ruby driver collection object



298
299
300
# File 'lib/mongo_mapper/document.rb', line 298

def collection
  database.collection(collection_name)
end

#collection_nameString

Returns the collection name, if not set, defaults to class name tableized

Returns:

  • (String)

    the collection name, if not set, defaults to class name tableized



293
294
295
# File 'lib/mongo_mapper/document.rb', line 293

def collection_name
  @collection_name ||= self.to_s.tableize.gsub(/\//, '.')
end

#connectionMongo::Connection #connection(mongo_connection) ⇒ Mongo::Connection

Overloads:

  • #connectionMongo::Connection

    Returns the connection used by your document class.

    Returns:

    • (Mongo::Connection)

      the connection used by your document class

  • #connection(mongo_connection) ⇒ Mongo::Connection

    Returns a new Mongo::Connection for yoru document class.

    Parameters:

    • mongo_connection (Mongo::Connection)

      a new connection for your document class to use

    Returns:

    • (Mongo::Connection)

      a new Mongo::Connection for yoru document class



247
248
249
250
251
252
253
254
# File 'lib/mongo_mapper/document.rb', line 247

def connection(mongo_connection=nil)
  if mongo_connection.nil?
    @connection ||= MongoMapper.connection
  else
    @connection = mongo_connection
  end
  @connection
end

#count(options = {}) ⇒ Object



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

def count(options={})
  collection.find(to_criteria(options)).count
end

#create(doc_attributes) ⇒ Boolean #create(docs_attributes) ⇒ Boolean

Returns when a document is successfully created, true will be returned. If a document fails to create, false will be returned.

Examples:

Creating a single document

MyModel.create({ :foo => "bar" })

Creating multiple documents

MyModel.create([{ :foo => "bar" }, { :foo => "baz" })

Overloads:

  • #create(doc_attributes) ⇒ Boolean

    Create a single new document

    Parameters:

    • doc_attributes (Hash)

      key/value pairs to create a new document

  • #create(docs_attributes) ⇒ Boolean

    Create many new documents

    Parameters:

    • provide (Array<Hash>)

      many Hashes of key/value pairs to create multiple documents

Returns:

  • (Boolean)

    when a document is successfully created, true will be returned. If a document fails to create, false will be returned.



161
162
163
# File 'lib/mongo_mapper/document.rb', line 161

def create(*docs)
  initialize_each(*docs) { |doc| doc.save }
end

#create!(*docs) ⇒ Object

Raises:

See Also:

  • Document.create


168
169
170
# File 'lib/mongo_mapper/document.rb', line 168

def create!(*docs)
  initialize_each(*docs) { |doc| doc.save! }
end

#databaseMongo::DB

Returns the database the document should use. Defaults to

MongoMapper.database if other database is not set.

Returns:

  • (Mongo::DB)

    the mongo database instance



274
275
276
277
278
279
280
# File 'lib/mongo_mapper/document.rb', line 274

def database
  if database_name.nil?
    MongoMapper.database
  else
    connection.db(database_name)
  end
end

#database_nameString

Returns the database name

Returns:

  • (String)

    the database name



266
267
268
# File 'lib/mongo_mapper/document.rb', line 266

def database_name
  @database_name
end

#delete(*ids) ⇒ Object

Removes (“deletes”) one or many documents from the collection. Note that this will bypass any destroy hooks defined by your class.

Parameters:

  • ids (Array)

    the ID or IDs of the records you wish to delete



202
203
204
# File 'lib/mongo_mapper/document.rb', line 202

def delete(*ids)
  collection.remove(to_criteria(:_id => ids.flatten))
end

#delete_all(options = {}) ⇒ Object



206
207
208
# File 'lib/mongo_mapper/document.rb', line 206

def delete_all(options={})
  collection.remove(to_criteria(options))
end

#destroy(id) ⇒ Object #destroy(ids) ⇒ Object

Iterates over each document found by the provided IDs and calls their destroy method. This has the advantage of processing your document’s destroy call-backs.

Examples:

Destroying a single document

Person.destroy("34")

Destroying multiple documents

Person.destroy("34", "45", ..., "54")

# OR...

Person.destroy(["34", "45", ..., "54"])

Overloads:

  • #destroy(id) ⇒ Object

    Destroy a single document by ID

    Parameters:

    • id

      the ID of the document to destroy

  • #destroy(ids) ⇒ Object

    Destroy many documents by their IDs

    Parameters:

    • the (Array)

      IDs of each document you wish to destroy



231
232
233
# File 'lib/mongo_mapper/document.rb', line 231

def destroy(*ids)
  find_some(ids.flatten).each(&:destroy)
end

#destroy_all(options = {}) ⇒ Object



235
236
237
# File 'lib/mongo_mapper/document.rb', line 235

def destroy_all(options={})
  all(options).each(&:destroy)
end

#ensure_index(name_or_array, options = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/mongo_mapper/document.rb', line 36

def ensure_index(name_or_array, options={})
  keys_to_index = if name_or_array.is_a?(Array)
    name_or_array.map { |pair| [pair[0], pair[1]] }
  else
    name_or_array
  end

  MongoMapper.ensure_index(self, keys_to_index, options)
end

#exists?(options = {}) ⇒ Boolean

Returns:



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

def exists?(options={})
  !count(options).zero?
end

#find(*args) ⇒ Object



77
78
79
80
81
# File 'lib/mongo_mapper/document.rb', line 77

def find(*args)
  find!(*args)
rescue DocumentNotFound
  nil
end

#find(: first, options) ⇒ Object #find(: last, options) ⇒ Object #find(: all, options) ⇒ Object #find(ids, options) ⇒ Object

Overloads:

  • #find(: first, options) ⇒ Object

    See Also:

    • Document.first
  • #find(: last, options) ⇒ Object

    See Also:

    • Document.last
  • #find(: all, options) ⇒ Object

    See Also:

    • Document.all

Raises:

  • DocumentNotFound raised when no ID or arguments are provided



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/mongo_mapper/document.rb', line 58

def find!(*args)
  options = args.extract_options!
  case args.first
    when :first then first(options)
    when :last  then last(options)
    when :all   then find_every(options)
    when Array  then find_some(args, options)
    else
      case args.size
        when 0
          raise DocumentNotFound, "Couldn't find without an ID"
        when 1
          find_one!(options.merge({:_id => args[0]}))
        else
          find_some(args, options)
      end
  end
end

#find_by_id(id) ⇒ Object



131
132
133
# File 'lib/mongo_mapper/document.rb', line 131

def find_by_id(id)
  find_one(:_id => id)
end

#first(options = {}) ⇒ Object

Returns the first document in the ordered collection as described by options.

Parameters:

  • options (Hash) (defaults to: {})

    any conditions understood by FinderOptions.to_mongo_criteria

Returns:

  • the first document in the ordered collection as described by options

See Also:



101
102
103
# File 'lib/mongo_mapper/document.rb', line 101

def first(options={})
  find_one(options)
end

#key(*args) ⇒ Object



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

def key(*args)
  key = super
  create_indexes_for(key)
  key
end

#last(options = {}) ⇒ Object

Returns the last document in the ordered collection as described by options.

Parameters:

  • options (Hash) (defaults to: {})

    any conditions understood by FinderOptions.to_mongo_criteria

  • [String] (Hash)

    a customizable set of options

Returns:

  • the last document in the ordered collection as described by options

Raises:

  • Exception when no :order option has been defined



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

def last(options={})
  raise ':order option must be provided when using last' if options[:order].blank?
  find_one(options.merge(:order => invert_order_clause(options[:order])))
end

#paginate(options) ⇒ Object



83
84
85
86
87
88
89
90
91
92
# File 'lib/mongo_mapper/document.rb', line 83

def paginate(options)
  per_page      = options.delete(:per_page) || self.per_page
  page          = options.delete(:page)
  total_entries = count(options)
  pagination    = Pagination::PaginationProxy.new(total_entries, page, per_page)

  options.merge!(:limit => pagination.limit, :skip => pagination.skip)
  pagination.subject = find_every(options)
  pagination
end

#set_collection_name(name) ⇒ Object

Changes the collection name from the default to whatever you want

Parameters:

  • name (#to_s)

    the new collection name to use.



285
286
287
# File 'lib/mongo_mapper/document.rb', line 285

def set_collection_name(name)
  @collection_name = name
end

#set_database_name(name) ⇒ Object

Changes the database name from the default to whatever you want

Parameters:

  • name (#to_s)

    the new database name to use.



259
260
261
# File 'lib/mongo_mapper/document.rb', line 259

def set_database_name(name)
  @database_name = name
end

#single_collection_inherited?Boolean

Returns:



311
312
313
# File 'lib/mongo_mapper/document.rb', line 311

def single_collection_inherited?
  keys.has_key?('_type') && single_collection_inherited_superclass?
end

#single_collection_inherited_superclass?Boolean

Returns:



315
316
317
# File 'lib/mongo_mapper/document.rb', line 315

def single_collection_inherited_superclass?
  superclass.respond_to?(:keys) && superclass.keys.has_key?('_type')
end

#timestamps!Object

Defines a created_at and updated_at attribute (with a Time value) on your document. These attributes are updated by an injected update_timestamps before_save hook.



305
306
307
308
309
# File 'lib/mongo_mapper/document.rb', line 305

def timestamps!
  key :created_at, Time
  key :updated_at, Time
  class_eval { before_save :update_timestamps }
end

#update(id, attributes) ⇒ Object #update(ids_and_attributes) ⇒ Object

Examples:

Updating single document

Person.update(1, {:foo => 'bar'})

Updating multiple documents at once:

Person.update({'1' => {:foo => 'bar'}, '2' => {:baz => 'wick'}})

Overloads:

  • #update(id, attributes) ⇒ Object

    Update a single document

    Parameters:

    • id

      the ID of the document you wish to update

    • attributes (Hash)

      the key to update on the document with a new value

  • #update(ids_and_attributes) ⇒ Object

    Update multiple documents

    Parameters:

    • ids_and_attributes (Hash)

      each key is the ID of some document you wish to update. The value each key points toward are those applied to the target document



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

def update(*args)
  if args.length == 1
    update_multiple(args[0])
  else
    id, attributes = args
    update_single(id, attributes)
  end
end