Everyday Rails

Obfuscated URLs with the FriendlyId gem

By Aaron Sumner, March 11, 2011. File under: .

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
    end
  end

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).

What do you think? Follow along on on Mastodon, Facebook, or Bluesky to let me know what you think and catch my latest posts. Better yet, subscribe to my newsletter for updates from Everyday Rails, book picks, and other thoughts and ideas that didn't quite fit here.
Buy Me A Coffee

Test with confidence!

If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.

Newsletter

Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.