Shorten URL using Bitly in Rails 3.X

This is achieved by using an HTTP Redirect on a domain name that is short, which links to the web page that has a long URL. This is especially convenient for messaging technologies such as Twitter and Identical which severely limit the number of characters that may be used in a message.

Many web developers pass descriptive attributes in the URL to represent data hierarchies, command structures, transaction paths or session information. This can result in URLs that are hundreds of characters long and that contain complex character patterns. Such URLs are difficult to memorize and manually reproduce. As a result, long URLs must be copied-and-pasted for reliability. Thus, short URLs are more convenient for websites.

Step# 1

To begin with, create an account at bit.ly

Get your API key by the following URL

    “http://bit.ly/account/your_api_key/”

Step# 2

In rails 3.x

Write the following gems in your gemfile

  • gem ‘bitly’

     Run “bundle install”

Step# 3

Add the following code in your controller

     require ‘bitly’

Step# 4

Bitly recently released their version 3 API. From this 0.5.0 release, the gem will continue to work the same but also provide a V3 module, using the version 3 API. The standard module will become deprecated, as Bitly do not plan to keep the version 2 API around f orever.

To move to using the version 3 API, call in you top of the controller:

Bitly.use_api_version_3

Step# 5

To shorten a URL

         bitly = Bitly.new(‘your-bitly-user-id’,’your-bitly-api-key’)

         page_url = bitly.shorten(‘your-url’)

         shorten_url = page_url.short_url

It will generate the bitly URL similar to “http://bit.ly/7BWXcQ

Advertisements

2 thoughts on “Shorten URL using Bitly in Rails 3.X

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s