maraigue (owner)

Revisions

gist: 10715 Download_button fork
public
Description:
TinyURL library for Ruby
Public Clone URL: git://gist.github.com/10715.git
tinyurl.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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