Skip to content

Instantly share code, notes, and snippets.

@markmcspadden
Created April 8, 2011 06:30
Show Gist options
  • Save markmcspadden/909395 to your computer and use it in GitHub Desktop.
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
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