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

[Validate]