Class: Klient::Response

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(original_response, data = nil) ⇒ Response

Returns a new instance of Response.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/klient/response.rb', line 22

def initialize(original_response, data = nil)
  @status = original_response.code

  # If data arg is provided then it's a collection resource and the original
  # response is for the entire collection. We don't want that -- this is an
  # individual resource FOR the collection -- so the data arg is used in place
  # of the parsed body for the collection response.
  if data
    @original_response = nil
    @parsed_body = data
    @parsed_headers = nil
  else
    @original_response = original_response
    @body = @original_response.body
    @parsed_headers = @original_response.headers

    if @original_response.body.blank?
       @parsed_body = {}
    else
      @parsed_body = JSON.parse(@original_response.body)
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mth, *args, &block) ⇒ Object

TODO: This is dangerously wrong. It’s just a shortcut to get something working.



47
48
49
50
51
52
53
# File 'lib/klient/response.rb', line 47

def method_missing(mth, *args, &block)
  if mth.to_s =~ /http_(\d+)\?/
    status_code == $1.to_i
  else
    @parsed_body.send(mth)
  end
end

Instance Attribute Details

#original_responseObject (readonly)

Returns the value of attribute original_response.



4
5
6
# File 'lib/klient/response.rb', line 4

def original_response
  @original_response
end

#parsed_bodyObject (readonly)

Returns the value of attribute parsed_body.



4
5
6
# File 'lib/klient/response.rb', line 4

def parsed_body
  @parsed_body
end

#parsed_headersObject (readonly)

Returns the value of attribute parsed_headers.



4
5
6
# File 'lib/klient/response.rb', line 4

def parsed_headers
  @parsed_headers
end

#statusObject (readonly)

Returns the value of attribute status.



4
5
6
# File 'lib/klient/response.rb', line 4

def status
  @status
end

Instance Method Details

#bodyObject



6
7
8
# File 'lib/klient/response.rb', line 6

def body
  @original_response.body
end

#headersObject



18
19
20
# File 'lib/klient/response.rb', line 18

def headers
  @parsed_headers
end

#ok?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/klient/response.rb', line 10

def ok?
  (200..299).include?(status_code)
end

#respond_to_missing?(mth, *args) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/klient/response.rb', line 55

def respond_to_missing?(mth, *args)
  mth.to_s =~ /http_(\d+)\?/ || @parsed_body.respond_to?(mth) || super
end

#status_codeObject



14
15
16
# File 'lib/klient/response.rb', line 14

def status_code
  @original_response.code
end