Class: GunBroker::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/gun_broker/response.rb

Overview

Wrapper class for the GunBroker API response JSON.

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Response

Returns a new instance of Response.

Parameters:

  • response (Net::HTTPResponse)

    Response returned from the API.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/gun_broker/response.rb', line 6

def initialize(response)
  @response = response

  case @response
  when Net::HTTPOK, Net::HTTPSuccess
    @data = JSON.parse(@response.body)
  when Net::HTTPUnauthorized
    raise GunBroker::Error::NotAuthorized.new(@response.body)
  when Net::HTTPNotFound
    raise GunBroker::Error::NotFound.new(@response.body)
  else
    raise GunBroker::Error::RequestError.new(@response.body)
  end
end

Instance Method Details

#[](key) ⇒ String, ...

Returns Whatever object is the value of key or nil if the key doesn't exist.

Parameters:

  • key (String)

    Key from the response JSON to read.

Returns:

  • (String, Array, Hash)

    Whatever object is the value of key or nil if the key doesn't exist.



23
24
25
# File 'lib/gun_broker/response.rb', line 23

def [](key)
  @data[key]
end

#bodyHash

Returns The response body as a Hash.

Returns:

  • (Hash)

    The response body as a Hash.



28
29
30
# File 'lib/gun_broker/response.rb', line 28

def body
  @data
end

#fetch(key) ⇒ Object

Like Hash#fetch

Parameters:

  • A (Object)

    key from the response JSON.

Returns:

  • (Object)

    The value for key.

Raises:

  • (KeyError)

    If key is not in the response.



36
37
38
# File 'lib/gun_broker/response.rb', line 36

def fetch(key)
  @data.fetch(key)
end