class ShortURL::Service

Attributes

action[RW]
block[RW]
code[RW]
field[RW]
method[RW]
port[RW]
response_block[RW]
ssl[RW]

Public Class Methods

new(hostname) { |service| ... } click to toggle source

Intialize the service with a hostname (required parameter) and you can override the default values for the HTTP port, expected HTTP return code, the form method to use, the form action, the form field which contains the long URL, and the block of what to do with the HTML code you get.

   # File lib/shorturl/service.rb
15 def initialize(hostname) # :yield: service
16   @hostname = hostname
17   @port = 80
18   @code = 200
19   @method = :post
20   @action = "/"
21   @field = "url"
22   @ssl = false
23 
24   if block_given?
25     yield self
26   end
27 end

Public Instance Methods

call(url) click to toggle source

Now that our service is set up, call it with all the parameters to (hopefully) return only the shortened URL.

   # File lib/shorturl/service.rb
31 def call(url)
32   http = Net::HTTP.new(@hostname, @port)
33   http.use_ssl = @ssl
34   http.verify_mode = OpenSSL::SSL::VERIFY_NONE
35 
36   http.start do
37     response = case @method
38                when :post
39                  http.post(@action, "#{@field}=#{CGI.escape(url)}")
40                when :get
41                  http.get("#{@action}?#{@field}=#{CGI.escape(url)}")
42                end
43 
44     if response.code == @code.to_s
45       on_response(response)
46     end
47   end
48 rescue Errno::ECONNRESET => e
49   raise ServiceNotAvailable, e.to_s, e.backtrace
50 end
on_body(body) click to toggle source

Extracts the shortened URL from a response body.

   # File lib/shorturl/service.rb
53 def on_body(body)
54   body
55 end
on_response(response) click to toggle source

Extracts the shortened URL from the response.

   # File lib/shorturl/service.rb
58 def on_response(response)
59   on_body(response.read_body)
60 end