Class: RightScale::CloudApi::HTTPResponse

Inherits:
HTTPParent show all
Defined in:
lib/base/helpers/http_response.rb

Overview

A Wrapper around standard Net::HTTPRsponse class

The class supports some handy methods for managing the code, the body and the headers. And everythig else can be accessed through raw attribute that points to the original Net::HTTPResponse instance.

Constant Summary collapse

BODY_BYTES_TO_LOG =

Body bytes to log

2000
BODY_BYTES_TO_LOG_ERROR =

Body bytes to log in case of error

6000

Instance Attribute Summary collapse

Attributes inherited from HTTPParent

#body, #raw

Instance Method Summary collapse

Methods inherited from HTTPParent

#[], #headers, #headers_info, #is_io?

Constructor Details

#initialize(code, body, headers, raw) ⇒ Rightscale::CloudApi::HTTPResponse

Constructor

Examples:

new('200', 'body', {}, object)

Parameters:

  • code (String)

    The http response code.

  • body (String, IO, Nil)

    The response body.

  • headers (Hash)

    The response headers.

  • raw (Net::HTTPRequest)

    The original response (optional).



64
65
66
67
68
69
# File 'lib/base/helpers/http_response.rb', line 64

def initialize(code, body, headers, raw)
  @code    = code.to_s
  @body    = body
  @raw     = raw
  @headers = HTTPHeaders::new(headers)
end

Instance Attribute Details

#codeString (readonly)

The response code

Examples:

response.code #=> '404'

Returns:



43
44
45
# File 'lib/base/helpers/http_response.rb', line 43

def code
  @code
end

Instance Method Details

#body_infoString

Displays the body information

Examples:

ec2.response.body_info #=> 'response boby'

Returns:



113
114
115
116
117
118
# File 'lib/base/helpers/http_response.rb', line 113

def body_info
  if    is_io?    then "#{body.class.name}"
  elsif is_error? then "size: #{body.to_s.size}, first #{BODY_BYTES_TO_LOG_ERROR} bytes:\n#{body.to_s[0...BODY_BYTES_TO_LOG_ERROR]}"
  else                 "size: #{body.to_s.size}, first #{BODY_BYTES_TO_LOG} bytes:\n#{body.to_s[0...BODY_BYTES_TO_LOG]}"
  end
end

#is_error?Boolean

Returns true if the response code is in the range of 4xx or 5xx

Examples:

response.is_error? #=> false

Returns:

  • (Boolean)


78
79
80
# File 'lib/base/helpers/http_response.rb', line 78

def is_error?
  !!(code.is_a?(String) && code.match(/^(5..|4..)/))
end

#is_redirect?Boolean

Returns true if the response code is in the range of 3xx

Examples:

response.is_redirect? #=> false

Returns:

  • (Boolean)


89
90
91
# File 'lib/base/helpers/http_response.rb', line 89

def is_redirect?
  !!(code.is_a?(String) && code.match(/^3..$/))
end

#to_sString

Returns the response code and code name

Examples:

ec2.response.to_s #=> '200 OK'

Returns:



100
101
102
103
104
# File 'lib/base/helpers/http_response.rb', line 100

def to_s
  result = code.dup
  result << " #{raw.class.name[/Net::HTTP(.*)/] && $1}" if raw.is_a?(Net::HTTPResponse)
  result
end