Hi, I’m Josh Symonds

I blog about Ruby on Rails, coding, and servers

Ruby 1.9 Awesomeness Part 1: SecureRandom

Reading time 1 minute

Ruby 1.9 includes a lot of neat stuff, and one of the coolest things is the SecureRandom module.

SecureRandom presents a plethora of useful methods for creating random numbers and strings. You can check out the documentation for a full list, but some of the more personally useful methods I’ve found are:

  • SecureRandom#uuid

    Dynamoid uses this method to generate random IDs for objects. The resulting random number is supposed to be unique across an enormously large namespace (see the RFC 4122 spec for details) and is perfect if you need a universally unique number… say, for generating IDs in a database.

  • SecureRandom#urlsafe_base64

    If you’re creating a URL shortener then this method will end up being incredibly useful. The resulting string only includes characters that are URL safe (as the method name suggests), and while the string is not as unique as one generated by UUID, it will still be fairly random. Guaranteeing uniqueness across an application with a small loop would still probably be a wise idea though:

1
2
3
4
permalink = loop do
  permalink = SecureRandom.urlsafe_base64(6)
  break permalink unless Model.find_by_permalink(permalink)
end
  • SecureRandom#base64

    As above, except that +, /, and = are included in the output. The addition of three more characters significantly improves the randomness of this method, though, so use it when the resulting string doesn’t need to be in a URL.

Regardless of what you’re working on, the new SecureRandom stuff will end up being incredibly useful for you. Go check out the documentation to see some of the other neat stuff it includes!