Class: Fattura24::Api::Response

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

Overview

An instance of this class will be returned on every api call, wrapping the content of the response and providing helper methods to navigate it’s content.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_response) ⇒ Response

Returns a new instance of Response.



16
17
18
# File 'lib/fattura24/api/response.rb', line 16

def initialize(http_response)
  @http_response = http_response
end

Instance Attribute Details

#http_responseObject (readonly)

When needed, you can directly access the underlying Net::HTTP response by calling this method.



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

def http_response
  @http_response
end

Instance Method Details

#codeObject

Returns the Integer value of the underlying http request. It does not mean the request performed it’s intended purpose. Make sure you use to_s or to_h to explore the actual body of the response.



32
33
34
# File 'lib/fattura24/api/response.rb', line 32

def code
  http_response&.code.to_i
end

#pdf?Boolean

Returns true when the body of the request contains a pdf file.

Returns:

  • (Boolean)


38
39
40
# File 'lib/fattura24/api/response.rb', line 38

def pdf?
  http_response&.content_type&.underscore == 'application/pdf'
end

#success?Boolean

Returns true when the http response is 200, false otherwise.

Returns:

  • (Boolean)


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

def success?
  code == 200
end

#to_hObject

Returns an hash representation of the xml body of the response. Raises NotSerializable in case of a binary (pdf file) content.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/fattura24/api/response.rb', line 46

def to_h
  if pdf?
    raise(
      Fattura24::NotSerializable,
      'Cannot create hash from binary file'
    )
  end

  Hash.from_xml(http_response&.body)
    &.deep_transform_keys do |key|
      key.to_s.underscore.to_sym
    end
end

#to_sObject

Returns the String body of this response. This can be both the original xml on most of the calls or the content of the pdf file when get_file is called.



65
66
67
# File 'lib/fattura24/api/response.rb', line 65

def to_s
  http_response&.body.to_s
end