Tag Archives: Bit.ly

URL Shortening on Rails 3 with Bit.ly

For integrating with twitter you need to shorten url. I have used this gem

First add gem to your gemfile

gem bitly

and run

bundle install

Now add this to your controller

require ‘bitly’

philnash’s gem has support for the bit.ly version 2 and version 3 api. I have use version 3.

Create a new file config\initializers\bitly.rb and write this.

Bitly.configure do |config|
  config.api_version = 3
  config.login = "##############"
  config.api_key = "##################################"
end

That’s it from installation.

Here is code from controller. This is the example from the gem documentation

u = bitly.shorten('http://www.google.com') #=> Bitly::Url

u.long_url #=> "http://www.google.com"
u.short_url #=> "http://bit.ly/Ywd1"
u.bitly_url #=> "http://bit.ly/Ywd1"
u.jmp_url #=> "http://j.mp/Ywd1"
u.user_hash #=> "Ywd1"
u.hash #=> "2V6CFi"
u.info #=> a ruby hash of the JSON returned from the API
u.stats #=> a ruby hash of the JSON returned from the API

Based on this your result is expected. if you want the short url try

bitly.shorten("http://domain.com/articles/#{id}").short_url

That’s it. Happy coding 🙂