url_hash

A simple little library for converting integers to X-character hashes, suitable for uses in urls. Hashes may or may not be encrypted, depending on usage.

Sample uses (inside Rails projects):

  1. Shortening urls for commonly used models. Add something like this to the bottom of your routes.rb:

match ':hash', :constraints => {:hash => /.{8}/},
  :to => redirect { |params| "/models/#{UrlHash.from_hash(params[:hash])}" }

And something like this to your model

class Model ...
  def hash
    save! if new_record?
    UrlHash.to_hash(self.id)
  end
end

Notes:

  1. A Short URL service. We store a map from hashes to urls in the database. Something like:

class ShortUrl < ActiveRecord::Base
  validates_presence_of :url
  validates_uniqueness_of :url

  def self.find_by_hash(hash, opts = {})
    # use conditions rather than a find so that we don't throw an exception
    find :first, {:conditions => {:id => UrlHash.from_hash(hash)}}.merge(opts)
  end

  def hash
    save! if new_record?
    UrlHash.to_hash(self.id)
  end
end

And something like (in routes.rb)

match ':hash', :constraints => {:hash => /.{8}/},
  :to => redirect { |params| ShortUrl.find_by_hash(params[:hash]).url }

Notes:

Contributing to url_hash

Copyright © 2011 Tom Coleman. See LICENSE.txt for further details.