Implementation of Shorten URL using Bitly in Rails 3.x

URL shortening is a technique on the World Wide Web in which a Uniform Resource Locator (URL) may be made substantially shorter in length and still direct to the required page.

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 may be more convenient for websites.

Step#1

First create an account at bit.ly  “https://bitly.com/a/sign_up?rd=/”
Get your API key by thefollowing 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 forever.

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.shorten

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

Advertisements