Created
October 7, 2010 05:44
-
-
Save zh/614616 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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