April 30th 2010

RedirectFollower Rubygem

Today I've been thinking about a small Twitter-based project which involves urls posted by people there. Those urls use some url shortening service like bit.ly in most cases - but I needed the actual destinations for those links. I ended up stealing code from John Nunemaker, wrapping it up into a Ruby gem and releasing version 0.1.0 of RedirectFollower. You can find the source code on GitHub.

Actually, I modified the source code a bit so you don't have to hit "resolve" manually after initializing the RedirectFollower. Also, there's a shorthand form.

After installing with gem install redirect_follower, you can either go the short way if you only want the url of the destination, or initialize a new instance of RedirectFollower to get the Net::HTTP response with status, body and all that malarkey.

require 'redirect_follower'  
RedirectFollower('http://bit.ly/cteFsP') 
# => Will return 'http://github.com/colszowka/redirect_follower'

Full-on mode:

require 'redirect_follower'  
redirect = RedirectFollower.new('http://bit.ly/cteFsP')

# Will print 'http://github.com/colszowka/redirect_follower'
puts redirect.url 

# Will print a lot of HTML
puts redirect.body 

# Returns the Net::HTTPResponse (well actually, a subclass for the respective HTTP 
# status of the destination)
redirect.response

You can limit the amount of redirects by giving a second parameter:

require 'redirect_follower'  
RedirectFollower('http://bit.ly/cteFsP', 2) 

This will raise RedirectFollower::TooManyRedirects when there are more than two redirects. The default limit is 5.

Offtopic:

I know I was supposed to write an article about my crazy new ruby blog software serious, that's going to arrive anytime soon. I figured this time I'm gonna write the article about a new Rubygem of mine straight after release so I don't end up not doing it at all. Regarding that serious article, I am planning to do an introductory screencast, but did not get past creating a linux tool that makes typewriter sounds when typing. Hopefully, I'll actually make use of it soon!

Written by Christoph Olszowka
blog comments powered by Disqus