Skip to content

Instantly share code, notes, and snippets.

@dblock
Created April 17, 2014 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dblock/11009220 to your computer and use it in GitHub Desktop.
Save dblock/11009220 to your computer and use it in GitHub Desktop.
Keep track of global counters in MongoDB.
module Counters
def self.next_sequence(name, increment = 1)
# find and increment (or initialize) counter
counter = collection.find(_id: name).modify({ '$inc' => { seq: increment } }, upsert: true, new: true)
# return new counter value
counter['seq']
end
private
def self.collection
Mongoid.default_session['counters']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment