Using Bit.ly and Ruby on Rails to Shorten a URL

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. Bit.ly 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 bit.ly and then go to the following URL to retrieve you key: http://bit.ly/account/your_api_key/

To shorten a URL:

bitly = Bitly.new('your-bitly-user-id','your-bitly-api-key')
page_url = bitly.shorten('www.marketingformavens.com')
page_url.shorten => http://bit.ly/7BWXcQ

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

To display stats in your dashboard use the following code:

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

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

Tags: , ,

2 Responses to “Using Bit.ly and Ruby on Rails to Shorten a URL”

  1. I am familiar with bitly. But i was not knowing how to use it with ruby on rails. Thanks for sharing!