Class Service
In: lib/shorturl.rb
Parent: Object

Methods

call   new  

Attributes

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

Public Class methods

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.

[Source]

    # File lib/shorturl.rb, line 18
18:   def initialize(hostname) # :yield: service
19:     @hostname = hostname
20:     @port = 80
21:     @code = 200
22:     @method = :post
23:     @action = "/"
24:     @field = "url"
25:     @block = lambda { |body| }
26: 
27:     if block_given?
28:       yield self
29:     end
30:   end

Public Instance methods

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

[Source]

    # File lib/shorturl.rb, line 34
34:   def call(url)
35:     Net::HTTP.start(@hostname, @port) { |http|
36:       response = case @method
37:                  when :post: http.send(@method, @action, "#@field=#{url}")
38:                  when :get: http.send(@method, "#@action?#@field=#{CGI.escape(url)}")
39:                  end
40:       if response.code == @code.to_s
41:         @block.call(response.read_body)
42:       end
43:     }
44:   end

[Validate]