Generating Guids in Ruby

Sam Saffron picture Sam Saffron · Jul 13, 2009 · Viewed 91k times · Source

I have problem that is really easily solved with Guids.

In particular, for a password reset workflow, I would like to send a Guid token to a user's email and have them reset their password using the token. Since guids are unique, this is pretty secure and saves me emailing people passwords, which is risky.

I noticed there is one Guid gem for Ruby; but it looks quite old, and it writes stuff to the file system.

Does anyone know of any other gems that can create a globally unique identifier?

I know I can just fall back to:

(0..16).to_a.map{|a| rand(16).to_s(16)}.join 

But it does not really seem like a proper GUID ...

Answer

J _ picture J _ · Mar 5, 2012

As of Ruby 1.9, uuid generation is built-in. Use the SecureRandom.uuid function.

For example:

require 'securerandom'
SecureRandom.uuid # => "96b0a57c-d9ae-453f-b56f-3b154eb10cda"