Skip to content

Instantly share code, notes, and snippets.

@mickey24
Created February 24, 2011 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickey24/842257 to your computer and use it in GitHub Desktop.
Save mickey24/842257 to your computer and use it in GitHub Desktop.
shorten a URL by bit.ly API ( http://bit.ly/hKSXnN )
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require "net/http"
require "cgi"
require "nkf"
require "json"
class Bitly
def initialize(account, api_key)
@account = account
@api_key = api_key
end
def shorten(url)
query = "longUrl=#{CGI.escape(NKF.nkf("-w -m0", url))}&login=#{@account}&apiKey=#{@api_key}"
response = Net::HTTP.get("api.bit.ly", "/v3/shorten?#{query}")
data = JSON.parse(response)
data["data"]["url"]
end
end
if __FILE__ == $PROGRAM_NAME
account = "account_name"
api_key = "**********************************"
bitly = Bitly.new(account, api_key)
puts bitly.shorten("http://www.google.com/") #=> "http://bit.ly/4xKkAW"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment