SecureRandom -- Stop writing your own random number and string generators
Stop writing your own random string generators. Rails does this for you.
In many code bases I’ll see something like this:
1 2 3 4 5 6 7 8 9 |
require 'digest/sha1' def generate_temporary_password self.password = Digest::SHA1.hexdigest(Time.now.to_s.split(//).sort_by{rand}.join) end |
This is gratuitous, since Ruby 1.9 and Ruby 1.8 with ActiveSupport give this to you for free. For the specifics, see this commit by Hongli.
Outside of Rails, you can use it like this:
1 2 3 4 5 6 7 8 |
>> require 'active_support/secure_random' => true >> ActiveSupport::SecureRandom.hex(10) => "8a2cf0a838e64f6f85d1" >> ActiveSupport::SecureRandom.base64(10) => "fUL81hGd77YyGg==" |
Inside of Rails, you can use it like this:
1 |
SecureRandom.hex(10) |
September 22, 2009

