mongomapper_plugins 0.0.4 → 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
@@ -27,3 +27,19 @@ This plugin will update the internal value of a model when using modifiers like
27
27
  counter => Counter.create(:count => 1)
28
28
  counter.increment(:count, 1)
29
29
  counter.count #=> 2
30
+
31
+ == Auto increment ids
32
+
33
+ This plugin will allow the auto generation of numeric ids
34
+ Uses the "Insert if Not Present" technique (see Mongo documentation[http://www.mongodb.org/display/DOCS/Atomic+Operations#AtomicOperations-%22InsertifNotPresent%22])
35
+
36
+ ====Usage
37
+
38
+ class Model
39
+ include MongoMapper::Document
40
+ auto_increment_id
41
+ end
42
+
43
+ #Assuming the first document in the collection
44
+ Model.create.id #=> 1
45
+ Model.create.id #=> 2 etc
@@ -0,0 +1,36 @@
1
+ module MongoMapper
2
+ module Plugins
3
+ module AutoIncrementId
4
+ module ClassMethods
5
+ def auto_increment_id
6
+ key :_id, Integer
7
+
8
+ after_create :generate_document_id
9
+ end
10
+ end
11
+
12
+ module InstanceMethods
13
+ private
14
+ def generate_document_id(options={})
15
+ while true
16
+ oldest_number = self.class.fields(:_id).sort([[:_id, :descending]]).first.try(:id)
17
+ self.id = oldest_number.to_i + 1
18
+ begin
19
+ break if collection.insert({:_id => id}, :safe => true)
20
+ rescue Mongo::OperationFailure => e
21
+ #Ignored, trying to get the next key
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+ module Addition
28
+ def self.included(model)
29
+ model.plugin AutoIncrementId
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ MongoMapper::Document.append_inclusions MongoMapper::Plugins::AutoIncrementId::Addition
@@ -1,2 +1,3 @@
1
1
  require 'mongo_mapper/plugins/versioned_update'
2
2
  require 'mongo_mapper/plugins/updating_modifiers'
3
+ require 'mongo_mapper/plugins/auto_increment_id'
metadata CHANGED
@@ -2,7 +2,7 @@
2
2
  name: mongomapper_plugins
3
3
  version: !ruby/object:Gem::Version
4
4
  prerelease:
5
- version: 0.0.4
5
+ version: 0.0.5
6
6
  platform: ruby
7
7
  authors:
8
8
  - Andrew Timberlake
@@ -35,6 +35,7 @@ extra_rdoc_files:
35
35
  - README.rdoc
36
36
  files:
37
37
  - LICENSE
38
+ - lib/mongo_mapper/plugins/auto_increment_id.rb
38
39
  - lib/mongo_mapper/plugins/updating_modifiers.rb
39
40
  - lib/mongo_mapper/plugins/versioned_update.rb
40
41
  - lib/mongomapper_plugins/railtie.rb