Skip to content

Instantly share code, notes, and snippets.

@hubertlepicki
Created March 26, 2010 10:21
Show Gist options
  • Save hubertlepicki/344741 to your computer and use it in GitHub Desktop.
Save hubertlepicki/344741 to your computer and use it in GitHub Desktop.
# Unique, atomic sequential number generator using MongoMapper, MongoDB and Ruby.
# Usage:
# Helper::Sequence.next_value(:my_seq)
# => 1
# Helper::Sequence.next_value(:my_seq)
# => 2
# Helper::Sequence.next_value(:my_other_seq)
# => 1
# Helper::Sequence.next_value(:my_seq)
# => 3
class Helper::Sequence
include MongoMapper::Document
key :identifier, String
key :value, Integer
validates_presence_of :identifier
validates_uniqueness_of :identifier
def initialize(args={}, from_database=false)
super(args, from_database)
self.value ||= 0
end
def self.next_value(seq_identifier)
s = Helper::Sequence.first_or_create(identifier: seq_identifier.to_s)
o = OrderedHash.new
o["findandmodify"]="helper.sequences"
o["query"] = {"identifier"=>s.identifier}
o["sort"]={}
o["update"]={"$inc"=>{"value"=>1}}
o["new"] = true
MongoMapper.database.command(o)["value"]["value"]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment