Tim
Tim

Reputation: 1461

Generating unique 32-character strings in Rails 3

I have an Application model which has app_id and secret_key fields. What is the best way to generate unique app_ids?

I can use ActiveSupport:SecureRandom.hex(16) to generate an 32-char alpha-numeric string and there will probably be no other string like it. If done in this manner, should I also do a database check to see if there is a duplicate app_id or is this step unnecessary since the likelihood of that is infinitesimally small?

Or is there a better method?

Thanks!

Tim

Upvotes: 1

Views: 1134

Answers (2)

twmills
twmills

Reputation: 3015

I would check first.

Here's some code I've seen in devise used when generating a unique token (modified for your example):

loop do
  token = ActiveSupport::SecureRandom.hex 16
  break token unless find(:first, :token => token)
end

Line 162: https://github.com/plataformatec/devise/blob/master/lib/devise/models/authenticatable.rb

Upvotes: 2

jesse reiss
jesse reiss

Reputation: 4579

I would always double check, just to be sure. Put a unique index on app_id and it's all set. It's hard to guarantee uniqueness

However, you could build a string that is guaranteed to be unique.

string = ActiveSupport::SecureRandom.hex(16)
append = @app.id.to_s
string = string.slice(0, string.length - append.length) + append

So the first part is random, but it always ends with the database id column, which would have to be unique.

There are also likely variations of this that keep the random looking structure, e.g. using a Caesar Cipher or a simple numeric to alphabetic cipher.

Upvotes: 3

Related Questions