Last active
March 9, 2022 21:39
-
-
Save agnel/7c06d409915628b0ec1fbdc7ba83b395 to your computer and use it in GitHub Desktop.
A base 36 incrementing Counter Model for Mongoid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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