Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment