aren55555
aren55555

Reputation: 1717

Rails String Unique ID

I want to create a model that has a attribute that holds a string based unique identifier.

I only want the unique string to be 3 characters long and consist of letters of the alphabet (lower case only) and numbers.

How do I implement something like the above? How do I avoid collisions? I have looked into MD5, and that seems along the lines of what I want to accomplish - but shorter. I am willing to also seed it with a time if that make the approach deterministic.

I would love any feedback or pointers on this topic. Thanks!

EDIT: One solution that has been on my mind is creating a table full of every single permutation, then randomly selecting as needed from the table, and deleting once used. Is this a bad approach?

Upvotes: 2

Views: 642

Answers (3)

Pedro Nascimento
Pedro Nascimento

Reputation: 13886

This gem called alphadecimal might be able to help you.

Upvotes: 0

aren55555
aren55555

Reputation: 1717

So the solution I decided to roll with after reading some of the questions & answers is quite different than what anyone had suggested.

I created a table to store codes. I wrote a ruby script to populate this table with every 3 letter combo based on the characters I wanted to use. Then on my model I have a before_save method assign a code to the instance if a code has not yet been assigned.

This approach ensures that I will never have a collision when assigning a code in the before_save. The slowest part is the generation of the table, but since I only have to do this once I can deal with this.

Upvotes: 0

rb512
rb512

Reputation: 6948

Check out this SO thread; it's got plenty of good suggestions. Especially the last answer by Simone Carletti which points to this post.

There are quite a few options on the above post. The one I liked and might be useful for you is the use of rufus-mnemo gem

Upvotes: 1

Related Questions