Skip to content

Instantly share code, notes, and snippets.

@titanous
Created March 7, 2011 04:17
Show Gist options
  • Select an option

  • Save titanous/858062 to your computer and use it in GitHub Desktop.

Select an option

Save titanous/858062 to your computer and use it in GitHub Desktop.
Long URL finder
# Long URL finder
# Copyright 2011 Jonathan Rudenberg
# Licensed under the MIT License
#
# Usage:
# LongURL.find('http://t.co/tssMTwK') #=> "http://fuckyeahnouns.com/Bacon"
require 'net/http'
require 'uri'
class LongURL
REDIRECT_CODES = %w(300 301 302 303)
MAX_REDIRECTS = 5
attr_accessor :short_urls
def self.find(short_url)
new(short_url).find
end
def initialize(short_url)
@short_urls = []
@url = short_url
end
def find(uri = nil)
uri ||= @url
url = URI.parse(uri)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true if url.scheme == 'https'
response = http.request_head url.path.empty? ? '/' : url.path
if REDIRECT_CODES.include?(response.code)
@short_urls << uri
return uri if @short_urls.length > MAX_REDIRECTS
find(response['Location'])
else
return uri
end
rescue
return @url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment