Created
September 14, 2008 06:02
-
-
Save maraigue/10715 to your computer and use it in GitHub Desktop.
TinyURL library for Ruby
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 'cgi' | |
Net::HTTP.version_1_2 | |
module TinyURL | |
module_function | |
# Makes a URL short via TinyURL.com. | |
# returned value is the key of TinyURL.com. | |
# (the string after "http://tinyurl.com/".) | |
def convert(url) | |
newurl = nil | |
Net::HTTP.start('tinyurl.com') do |http| | |
response = http.get("/api-create.php?url=#{CGI.escape(url)}") | |
newurl = response.body | |
end | |
if newurl =~ /\Ahttp:\/\/tinyurl.com\// | |
$'.rstrip #'# | |
else | |
nil | |
end | |
end | |
# Gets the source URL from the key of TinyURL.com. | |
# For example, if "http://tinyurl.com/123456" is redirected to | |
# "http://some.url.com/", this method TinyURL.expand("123456") | |
# returns "http://some.url.com/". | |
def expand(key) | |
unless key =~ /\A[\-0-9A-Za-z]+\z/ | |
raise ArgumentError, "TinyURL key can contain only numbers, alphabets, and dashes." | |
end | |
header = nil | |
Net::HTTP.start('tinyurl.com') do |http| | |
response = http.get("/#{key}") | |
header = response['Location'] | |
end | |
header | |
end | |
end | |
if $0 == __FILE__ | |
# Make long URL short | |
source = 'http://www.google.com/' | |
tinyurl_key = TinyURL.convert(source) | |
puts "#{source} -> http://tinyurl.com/#{tinyurl_key}" | |
expanded = TinyURL.expand(tinyurl_key) | |
puts "http://tinyurl.com/#{tinyurl_key} -> #{expanded}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment