I'm trying to come with an algorithm to generate unique nonsequential tokens for a model in my rails app.
For instance:
MyModel.create.token #=> '183685'
MyModel.create.token #=> '456873'
MyModel.create.token #=> '813870'
The only way I can think to handle this is to create a random thing, check for a clash, and retry. This seems kind of code smelly to me, in a bute force kind of way.
class MyModel < ActiveRecord::Base
before_create :set_token
def set_token
existing_model_count = nil
# Loop while we have a token that already belongs to an existing model.
while existing_model_count.nil? || existing_model_count > 0
random_token = TokenGenerator.random_token
existing_model_count = MyModel.where(token: random_token).count
end
# Loop exited, meaning we found an unused token.
self.token = random_token
end
end
Is there a better way to do this that doesn't involve a while
loop which will iterate an unknown number of times?
While the examples here are ruby, this is sort of generic algorithmic issue which can apply to any language, so solutions in other languages are welcome.