Posts Tagged ‘url shortening’

Using and Ruby on Rails to Shorten a URL

Monday, January 4th, 2010

If you’re building a Rails application and you need to add a URL Shortening service then you should look at philnash’s bitly gem. is dominating the crowded URL Shortening category. Its dashboard provides statistics for each shortened URL which makes it a very valuable tool.

To get started simply type:

gem install bitly

In your controller you’ll want to add:

require 'bitly'

Finally, to use the service you’ll need an API key. First create an account at and then go to the following URL to retrieve you key:

To shorten a URL:

bitly ='your-bitly-user-id','your-bitly-api-key')
page_url = bitly.shorten('')
page_url.shorten =>

The URL has been shortened and you can display or use it in your application. You can also log into your dashboard and see detailed statistics on each URL.

To display stats in your dashboard use the following code:

page_url = bitly.shorten('', :history => 1)

For other options such as expanding a URL check out the documenation on github.