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 21
21:   def initialize(hostname) # :yield: service
22:     @hostname = hostname
23:     @port = 80
24:     @code = 200
25:     @method = :post
26:     @action = "/"
27:     @field = "url"
28:     @block = lambda { |body| }
29: 
30:     if block_given?
31:       yield self
32:     end
33:   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 37
37:   def call(url)
38:     Net::HTTP.start(@hostname, @port) { |http|
39:       response = case @method
40:                  when :post: http.post(@action, "#{@field}=#{url}")
41:                  when :get: http.get("#{@action}?#{@field}=#{CGI.escape(url)}")
42:                  end
43:       if response.code == @code.to_s
44:         begin
45:           @block.call(response.read_body)
46:         rescue NoMethodError
47:           nil
48:         end
49:       end
50:     }
51:   end

[Validate]