Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a short UUID string using uuidtools In Rails

Tags:

I have to generate a unique and random string which is to be stored in database. For doing this I have used the "uuidtools" gem. Then in my controller I have added the following line:

require "uuidtools" 

and then in my controllers create method I have declared a 'temp' variable and generating a unique and random 'uuid' string like this:

temp=UUIDTools::UUID.random_create 

which is creating a string like this one:

f58b1019-77b0-4d44-a389-b402bb3e6d50 

Now my problem is I have to make it short, preferably within 8-10 character. Now how do I do it?? Is it possible to pass any argument to make it a desirable length string??

Thanks in Advance...

like image 718
Siddharth Avatar asked Jan 07 '13 12:01

Siddharth


1 Answers

You don't need uuidtools for this. You can use Secure Random for this.

[1] pry(main)> require "securerandom" => true [2] pry(main)> SecureRandom.hex(20) => "82db4d707c4c5db3ebfc349da09c991b7ca0faa1" [3] pry(main)> SecureRandom.base64(20) => "CECjUqNvPBaq0o4OuPy8RvsEoCY=" 

Passing 4 and 5 to hex will generate 8 and 10 character hex strings respectively.

[5] pry(main)> SecureRandom.hex(4) => "a937ec91" [6] pry(main)> SecureRandom.hex(5) => "98605bb20a" 
like image 142
Dogbert Avatar answered Oct 18 '22 13:10

Dogbert