Following code can be used to Short urls in ruby or ruby on rails application.
I am using Google API for this.

require "rest_client"
require 'json'

# UrlShorther 
# Use it UrlShortner.shortner(link)
# It will return and sorted url "http://goo.gl/J4p9jd"

class UrlShortner
  def self.shortner(link)
    begin
     response = RestClient.post('https://www.googleapis.com/urlshortener/v1/url?key=GOOGLE_API_KEY', 
                {"longUrl" => link }.to_json, headers = {'Content-Type' => 'application/json'})
     response = JSON.parse response
     shortned_url = response["id"]
   rescue Exception => e
    e
   end
  end
end

Get this API KEY https://console.developers.google.com


Digital Ocean referral
Digital Ocean referral

Advertisements

One thought on “quick url shortner ruby

  1. You can also use gem ‘shorturl’ as by this you can convert longer url to tiny url or bitly url and so many other option is also available by this gem.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s