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