Fellow Stranger Fellow Stranger - 4 months ago 5x
Ruby Question

Check if there are any unique tokens left of a certain character length

I have a Post model with the attribute


I'm using
to create a token.

The token doesn't need to be unguessable, but must be unique.

I'm starting with tokens 1 character long, and when they are all used up (all 64 combinations), I should move on to have tokens that are 2 characters long.

How should I check if there are any token variations left for tokens that are 3 characters long?


It would be something like :

64^n - Post.count(:token).where('char_length(token) = ?', n)

The first part gives the number of combinations possible and the second the number of records with a token length of n.

But don't forget that your random generator won't necessarily generate the remaining possible combinations. There will be exponentially more and more collisions over the time, therefore I'd strongly discourage this kind of implementation.

Note: The char_length statement is MySQL specific, so depending on your RDBMS, you'll have to adapt this part.