Class: Cybertrain::HttpClient::Response

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/http_client.rb

Overview

A response: the status, the headers (names in lowercase) and the body. A streamed response (a block, #get_to_file) has an empty body.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#body ⇒ String (readonly)

The body as received (chunked transfer coding removed), a byte String: binary under CRuby, as Net::HTTP’s is.

Returns:

  • (String)


133
134
135
# File 'cybertrain/http_client.rb', line 133

def body
  @body
end

#bytes_written ⇒ Integer (readonly)

The bytes Cybertrain::HttpClient#get_to_file wrote to the file; 0 for every other form.

Returns:



139
140
141
# File 'cybertrain/http_client.rb', line 139

def bytes_written
  @bytes_written
end

#headers ⇒ Hash{String => String} (readonly)

Header names are lowercase; a header sent more than once has its values joined with “, “.

Returns:

  • (Hash{String => String})


127
128
129
# File 'cybertrain/http_client.rb', line 127

def headers
  @headers
end

#status ⇒ Integer (readonly)

Returns e.g. 200.

Returns:



121
122
123
# File 'cybertrain/http_client.rb', line 121

def status
  @status
end

Instance Method Details

#header(name) ⇒ String?

Parameters:

  • name (String) —

    any case

Returns:

  • (String, nil)


170
171
172
# File 'cybertrain/http_client.rb', line 170

def header(name)
  @headers[name.to_s.downcase]
end

#json_array ⇒ Array<Object>

The body parsed as a JSON array.

Returns:

  • (Array<Object>) —

    [] when the body is not a JSON array



161
162
163
164
165
# File 'cybertrain/http_client.rb', line 161

def json_array
  text = @body
  parsed = Cast.parse_json(text)
  Cast.array(parsed)
end

#json_hash ⇒ Hash{String => Object}

The body parsed as a JSON object.

Examples:

name = client.get(url).json_hash["name"]

Returns:

  • (Hash{String => Object}) —

    {} when the body is not a JSON object (an array, a scalar, not JSON, empty)



154
155
156
# File 'cybertrain/http_client.rb', line 154

def json_hash
  Cast.json_hash(@body)
end

#success? ⇒ Boolean

Returns true for a 2xx status.

Returns:

  • (Boolean) —

    true for a 2xx status



176
177
178
# File 'cybertrain/http_client.rb', line 176

def success?
  @status >= 200 && @status <= 299
end