Monday, April 14, 2008

Reverse Tinyurl with Ruby

I was searching for a way to reverse TinyURL's using Ruby. First, I went to to see if there was actually an API to do this. Unfortunately I did not find one. I then searched for Ruby APIs to do it and came upon these two libraries for dealing with TinyURL's:
  1. Tinyurl - This one converts regular URL's to TinyURL's and vice-versa. However, I examined the source code and discovered that to do this, the author's personal web server,, is called. This concerned me because: What if this service goes down? My program would stop working.

  2. ShortURL - This one converts original URL's into many "short URL" formats such as TinyURL, RubyURL, and mooURL. Unfortunately there is no way to reverse any of these URL's. Since I needed the reverse functionality, I had to pass this one by.
With a little more googling, I found the PHP code that the Tinyurl author used to do the TinyURL conversions. I decided to port his screen-scraping approach to Ruby for use in my program:

require 'rubygems'
require 'net/http'

def reverse_tinyurl(url)
url_parts = url.split('.com/')
preview_url = "{url_parts[1]}"
response = Net::HTTP.get_response(URI.parse(preview_url))
original_url = response.body.scan(/redirecturl" href="(.*)">/)[0][0]

puts reverse_tinyurl('')

Running this program would print out the URL to my blog,

By the way, I also found TinyURL Callback API in JavaScript, but I wanted a server-side solution. Additionally, I found the TinyURLReverser from Yahoo Pipes, but I wasn't clear on how this worked. I need to examine this one a little further.


Anonymous said...

Thanks so much for taking the time to port this code to Ruby. I'd been meaning to do that for ages! I've released your code as tinyurl 1.2.0 at Rubyforge.

Thanks again,
Logan Koester

PS - Following you on Twitter now - keep up the great work :-)

Ken Weiner said...

Glad I could be of help!

tiny url converter said...

I think I must use this php code given in your blog because i am also looking for the short URL converter through Google. You have shared good experience regarding this php code so I must try it once.