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:

  • You probably don’t need to encrypt in this case, unless your ids are private somehow.

  • It’d probably be better to use a metal to do this, rather than the route, as we don’t need any environmental stuff, take this code as pointer in the right direction.

  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:

  • You will want to use find_or_create_by_url to create the short_urls and, you’ll want an index on url.

  • If you have any kind of security based on URLs being difficult to guess, you’ll want to use encryption

Contributing to url_hash

  • Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet

  • Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it

  • Fork the project

  • Start a feature/bugfix branch

  • Commit and push until you are happy with your contribution

  • Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

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