Created
April 8, 2011 06:30
-
-
Save markmcspadden/909395 to your computer and use it in GitHub Desktop.
Ruby library for following out short urls to their end destination. LongUrl.new('http://t.co/fadsfs').longize
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 'net/http' | |
require 'uri' | |
class LongUrl | |
attr_accessor :short_url | |
attr_reader :long_url | |
def initialize(short_url) | |
@short_url = short_url | |
end | |
def longize | |
begin | |
response = fetch(short_url) | |
if response.is_a?(Net::HTTPOK) | |
self.long_url | |
else | |
raise NoLongUrlFound # This will never really happen since the fetch will error out first | |
end | |
rescue | |
nil | |
end | |
end | |
# This probably looks familiar if you've ever spent time with the Net::HTTP rdoc | |
def fetch(uri_str, limit = 10) | |
# You should choose better exception. | |
raise ArgumentError, 'HTTP redirect too deep' if limit == 0 | |
response = Net::HTTP.get_response(URI.parse(uri_str)) | |
case response | |
when Net::HTTPSuccess | |
@long_url = uri_str | |
response | |
when Net::HTTPRedirection | |
fetch(response['location'], limit - 1) | |
else | |
response.error! | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment