Skip to content

Instantly share code, notes, and snippets.

@agnel
Last active March 9, 2022 21:39
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 agnel/7c06d409915628b0ec1fbdc7ba83b395 to your computer and use it in GitHub Desktop.
Save agnel/7c06d409915628b0ec1fbdc7ba83b395 to your computer and use it in GitHub Desktop.
A base 36 incrementing Counter Model for Mongoid
module CounterIncrementor
def next(counter_name)
counter = self.find_by(name: counter_name)
counter.increment
end
end
class Counter
include Mongoid::Document
include Mongoid::Timestamps
extend CounterIncrementor
field :name, type: String
field :sequence_value, type: String, default: '0000000000'
def increment
set(sequence_value: self.inc_lamba.call(self.sequence_value), updated_at: Time.now)
end
def inc_lamba
->s{(s.to_i(36)+1).to_s(36).rjust 10,?0}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment