Class: TNT::Resource

Inherits:
OpenStruct
  • Object
show all
Extended by:
HTTP::RestClient::DSL
Defined in:
lib/tnt.rb

Overview

Base endpoint resources class

Direct Known Subclasses

Label, Manifest, Shipment

Constant Summary collapse

XML_HEADER =
'<?xml version="1.0" encoding="UTF-8"?>'.freeze
XML_RENDER_OPTIONS =
{
  unwrap: false, key_converter: :upcase, pretty_print: true
}

Class Method Summary collapse

Class Method Details

.credentialsHash

Returns a payload with service credentials

Returns:

  • (Hash)


22
23
24
25
26
27
28
29
# File 'lib/tnt.rb', line 22

def self.credentials
  {
    company: ENV['TNT_USERNAME'],
    password: ENV['TNT_PASSWORD'],
    appid: :EC,
    appversion: 3.0
  }
end

.error_response?(response, parsed) ⇒ TrueClass

Validate error response

Looks at the response code by default.

Parameters:

  • response (HTTP::Response)

    the server response

  • parsed (Object)

    the parsed server response

Returns:

  • (TrueClass)

    if status code is not a successful standard value



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

def self.error_response?(response, parsed)
  parsed.is_a?(Hash) && (
    parsed.dig('parse_error') ||
    parsed.dig('runtime_error') ||
    parsed.dig('document', 'error')
  ) || super
end

.extract_error(response, parsed) ⇒ String

Extracts the error message from the response

Parameters:

  • response (HTTP::Response)

    the server response

  • parsed (Object)

    the parsed server response

Returns:

  • (String)


61
62
63
64
65
66
# File 'lib/tnt.rb', line 61

def self.extract_error(response, parsed)
  parsed&.dig('runtime_error') ||
    parsed&.dig('parse_error') ||
    parsed&.dig('document', 'error')&.first ||
    super
end

.parse_response(response) ⇒ Object

Parses response (from XML)

Parameters:

  • response (HTTP::Response)

    object

Returns:

  • (Object)


72
73
74
75
76
# File 'lib/tnt.rb', line 72

def self.parse_response(response)
  Hash.from_xml(response.body.to_s).deep_transform_keys(&:downcase)
rescue StandardError
  [response.body.to_s.split(':')].to_h.deep_transform_keys(&:downcase)
end

.to_xml(data) ⇒ String

Renders a dictionary to XML

Parameters:

  • data (Hash)

    object to be rendered

Returns:

  • (String)


35
36
37
# File 'lib/tnt.rb', line 35

def self.to_xml(data)
  XML_HEADER + Gyoku.xml({ eshipper: data }, XML_RENDER_OPTIONS)
end