Skip to content

Instantly share code, notes, and snippets.

@zh
Created October 7, 2010 05:44
Show Gist options
  • Save zh/614616 to your computer and use it in GitHub Desktop.
Save zh/614616 to your computer and use it in GitHub Desktop.
require 'mechanize'
require 'singleton'
BASE = 'http://goo.gl/'.freeze
REDIR = "#{BASE}?authen=1".freeze
NOISE = "#{BASE}?url=".freeze
class GooAPI
include Singleton
def self.shorten(long_url, debug = false)
begin
@agent = Mechanize.new
@agent.user_agent_alias = 'Linux Mozilla'
@agent.get(BASE)
page = @agent.get(REDIR)
puts page.inspect if debug
form = page.forms[0]
form.url = long_url
page = @agent.submit(form)
return page.uri.to_s.sub(NOISE,'')
catch
return long_url
end
end
end
if $0 == __FILE__
unless ARGV[0]
puts "Usage: googl {long_url}"
exit(99)
end
puts GooAPI.shorten(ARGV[0])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment