Class: WebClient::Connection

Inherits:
Object
  • Object
show all
Includes:
Net
Defined in:
lib/web_client/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Connection

Returns a new instance of Connection.



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/web_client/connection.rb', line 6

def initialize(*args)
  if args.first.is_a? Hash
    options = args[0].inject({}) { |h, i| h[i[0].to_sym] = i[1]; h }
    host = options[:host]
    port = options[:port]
  else
    host = args[0]
    port = args[1]
  end
  @http = HTTP.new(host, port)
end

Instance Method Details

#hostObject



18
19
20
# File 'lib/web_client/connection.rb', line 18

def host
  @http.address
end

#portObject



22
23
24
# File 'lib/web_client/connection.rb', line 22

def port
  @http.port
end

#request(request, &block) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/web_client/connection.rb', line 54

def request(request, &block)
  begin
    request!(request, &block)
  rescue WebClient::Error => e
    nil
  end
end

#request!(request) ⇒ Object



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
# File 'lib/web_client/connection.rb', line 26

def request!(request)
  begin
    WebClient.logger.debug "[WebClient] #{request.type.to_s.upcase} Url: http://#{host}#{(port != 80) ? ":#{port}" : ''}#{request.url} | Body: #{request.body} | Headers: #{request.headers}"
    response = Response.new @http.request(request.to_http)
    WebClient.logger.debug "[WebClient] RESPONSE Status: #{response.code} | Content: #{response.body}"

    unless response.success?
      WebClient.logger.error "[WebClient] #{response.code} - Unexpected error\n#{response.body}"
      raise Error, response.body ? response.body.force_encoding('utf-8') : 'Unexpected error'
    end

    block_given? ? yield(response) : response

  rescue Timeout::Error,
      Errno::EHOSTUNREACH,
      Errno::EINVAL,
      Errno::ECONNRESET,
      EOFError,
      HTTPBadResponse,
      HTTPHeaderSyntaxError,
      ProtocolError,
      SocketError,
      Errno::ECONNREFUSED => e
    WebClient.logger.error "[WebClient] #{e.class}: #{e.message}\nServer: #{host}:#{port}\nRequest: #{request.to_json}"
    raise ConnectionFail, e
  end
end