Class: MongomapperId2::Incrementor::Sequence
- Inherits:
-
Object
- Object
- MongomapperId2::Incrementor::Sequence
- Defined in:
- lib/incrementor.rb
Instance Method Summary collapse
- #collection ⇒ Object
- #create(number = 0) ⇒ Object
- #current ⇒ Object
- #db ⇒ Object
- #exists? ⇒ Boolean
- #inc ⇒ Object
-
#initialize(sequence) ⇒ Sequence
constructor
A new instance of Sequence.
- #query ⇒ Object
- #set(number) ⇒ Object
- #update_number_with(mongo_func) ⇒ Object
Constructor Details
#initialize(sequence) ⇒ Sequence
Returns a new instance of Sequence.
5 6 7 8 |
# File 'lib/incrementor.rb', line 5 def initialize(sequence) @sequence = sequence.to_s exists? || create end |
Instance Method Details
#collection ⇒ Object
18 19 20 |
# File 'lib/incrementor.rb', line 18 def collection db['sequences'] end |
#create(number = 0) ⇒ Object
27 28 29 |
# File 'lib/incrementor.rb', line 27 def create(number = 0) collection.insert(query.merge({ "number" => number })) end |
#current ⇒ Object
21 22 23 |
# File 'lib/incrementor.rb', line 21 def current collection.find_one(query)["number"] end |
#db ⇒ Object
12 13 14 |
# File 'lib/incrementor.rb', line 12 def db MongoMapper.database # replace this if you're not using MongoMapper end |
#exists? ⇒ Boolean
9 10 11 |
# File 'lib/incrementor.rb', line 9 def exists? collection.find(query).count > 0 end |
#inc ⇒ Object
24 25 26 |
# File 'lib/incrementor.rb', line 24 def inc update_number_with("$inc" => { "number" => 1 }) end |
#query ⇒ Object
15 16 17 |
# File 'lib/incrementor.rb', line 15 def query { "seq_name" => @sequence } end |
#set(number) ⇒ Object
30 31 32 |
# File 'lib/incrementor.rb', line 30 def set(number) update_number_with("$set" => { "number" => number }) end |
#update_number_with(mongo_func) ⇒ Object
33 34 35 36 37 38 39 40 |
# File 'lib/incrementor.rb', line 33 def update_number_with(mongo_func) opts = { "query" => query, "update" => mongo_func, "new" => true # return the modified document } collection.find_and_modify(opts)["number"] end |