Obfuscated URLs with the FriendlyId gem

March 11, 2011

As I’ve mentioned in the past, I’m a big fan of the FriendlyId gem for easily creating human-readable, search engine-friendly URLs. But what if you want to make something that’s not so human or search engine friendly? Here’s one simple way to get something up and running.

For this demonstration, I’ll be using the FriendlyId gem’s ability to use a custom method for a slug. (I’m assuming you’ve installed and configured FriendlyId as dictated by the gem’s instructions.) What I’m doing here is creating a SHA1 hash of a secret’s name field. You could, of course, use any unique field that’s not going to change (though FriendlyId should remember old slugs, if necessary), or use your own encryption technique.

  # app/models/secret.rb; this would go in the model you want to obfuscate
  class Secret < ActiveRecord::Base
    has_friendly_id :code, :use_slug => true

    validates :name, :uniqueness => true

    def code
       Digest::SHA1.hexdigest self.name

Like I said, it’s simple. If your security needs are serious you’d probably want something a little more complex (not to mention more layered than a basic obfuscation technique), but I wanted to share an out-of-the-box way to use a gem that already exists (and may even be in use in your app already).

Rails testing made simple

Learn to test Rails apps the way I learned, building up tests step-by-step, in Everyday Rails Testing with RSpec. Expanded to include exclusive content and a complete sample Rails application. Learn more »

blog comments powered by Disqus