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)



304
305
306
307
308
309
310
311
312
313
# File 'lib/mongo_mapper/document.rb', line 304

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:



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

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

#collectionObject

Returns the Mongo Ruby driver collection object.

Returns:

  • the Mongo Ruby driver collection object



282
283
284
# File 'lib/mongo_mapper/document.rb', line 282

def collection
  @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



277
278
279
# File 'lib/mongo_mapper/document.rb', line 277

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



241
242
243
244
245
246
247
248
# File 'lib/mongo_mapper/document.rb', line 241

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

#count(options = {}) ⇒ Object



129
130
131
# File 'lib/mongo_mapper/document.rb', line 129

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.



155
156
157
# File 'lib/mongo_mapper/document.rb', line 155

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

#create!(*docs) ⇒ Object

Raises:

See Also:

  • Document.create


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

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

#databaseMongo #database(name) ⇒ Mongo

Overloads:

  • #databaseMongo

    Returns the database object used by your document class.

    Returns:

    • (Mongo)

      the database object used by your document class

  • #database(name) ⇒ Mongo

    Returns a Mongo database object for the specified database.

    Parameters:

    • name (String)

      the name of an existing, or new, Mongo database

    Returns:

    • (Mongo)

      a Mongo database object for the specified database



256
257
258
259
260
261
262
263
# File 'lib/mongo_mapper/document.rb', line 256

def database(name=nil)
  if name.nil?
    @database ||= MongoMapper.database
  else
    @database = connection.db(name)
  end
  @database
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



196
197
198
# File 'lib/mongo_mapper/document.rb', line 196

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

#delete_all(options = {}) ⇒ Object



200
201
202
# File 'lib/mongo_mapper/document.rb', line 200

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



225
226
227
# File 'lib/mongo_mapper/document.rb', line 225

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

#destroy_all(options = {}) ⇒ Object



229
230
231
# File 'lib/mongo_mapper/document.rb', line 229

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:



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

def exists?(options={})
  !count(options).zero?
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



125
126
127
# File 'lib/mongo_mapper/document.rb', line 125

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:



95
96
97
# File 'lib/mongo_mapper/document.rb', line 95

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



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

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



77
78
79
80
81
82
83
84
85
86
# File 'lib/mongo_mapper/document.rb', line 77

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 = nil) ⇒ Object

Changes the collection name from the default to whatever you want

Parameters:

  • name (#to_s) (defaults to: nil)

    the new collection name to use. Defaults to nil



268
269
270
271
# File 'lib/mongo_mapper/document.rb', line 268

def set_collection_name(name=nil)
  @collection = nil
  @collection_name = name
end

#single_collection_inherited?Boolean

Returns:



295
296
297
# File 'lib/mongo_mapper/document.rb', line 295

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

#single_collection_inherited_superclass?Boolean

Returns:



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

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.



289
290
291
292
293
# File 'lib/mongo_mapper/document.rb', line 289

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



183
184
185
186
187
188
189
190
# File 'lib/mongo_mapper/document.rb', line 183

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