URL Shortening in Ruby on Rails

I was creating a project the other day that used anonymous pages for users and I wanted to make it a little less “guessable” but more human friendly than a SHA1 hash, so I decided to make a small home-brew URL shortener similar in format to Tiny URL.

The neat thing about ruby is that when you turn a Fixnum to a String with to_s you can specify the base, and when you turn a String back to a Fixnum you can also specify a base in to_i. This lends itself perfectly to turning (large) IDs into a shortened URL thats easier to remember.

In the first gist you can see how this would work with a model to make simple url shortening in rails – or, you can use randomized values to generate more user friendly “unique” tokens (as opposed to using SHA1 hashes for user confirmation/password reset pages).

# You can use the model's ID (PK/Serial) to generate a token which can be reversed:
# Example:
#   Url.find(7213).shortened        #=> 5kd
#   Url.find_by_shortened("5kd")    #=> #<Url id: 7213...>
class Url < ActiveRecord::Base
  Radix = 36
  
  # convert ID into a shortened version
  def shortened
    id.to_s(Radix)
  end

  # unconvert the shortened version back to an ID
  def self.shortened_to_id(shortened)
    shortened.to_i(Radix)
  end

  # convert and lookup
  def self.find_by_shortened(shortened)
    find shortened_to_id(shortened)
  end
end

Usage

# make tinyurl-ish tokens for pages so you dont have a goofy MD5 running amuck 
# Example:
#   make_token  #=> "32uelywr"
# NOTE: the longer the number, the longer the token
def make_token
  ("%d%d" % [rand(100), Time.now.to_i]).to_i.to_s(36)
end

View Gist