Class: DPD::Resource

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

Overview

Base endpoint resources class

Direct Known Subclasses

Pickup, Printout, Shipment, Track, Voucher

Class Method Summary collapse

Class Method Details

.credentialsHash

Returns a payload with service credentials

Returns:

  • (Hash)


18
19
20
21
22
23
# File 'lib/dpd.rb', line 18

def self.credentials
  {
    userName: ENV['DPD_USER'],
    password: ENV['DPD_PASSWORD']
  }
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



45
46
47
# File 'lib/dpd.rb', line 45

def self.error_response?(response, parsed)
  super || parsed.is_a?(Hash) && parsed.dig('error')
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)


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

def self.extract_error(response, parsed)
  parsed&.dig('error', 'message') || super
end

.parse_response(response) ⇒ Object

Will try to parse the response or return an IO if it’s a PDF

Will return nothing on failure.

Parameters:

  • response (HTTP::Response)

    the server response

Returns:

  • (Object)

    upon success



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/dpd.rb', line 66

def self.parse_response(response)
  if response.mime_type == 'application/pdf'
    io = Tempfile.new([name.underscore, '.pdf'])
    io.write(response.body)
    io.seek(0)

    { data: io }
  else
    super
  end
end

.request(verb, uri, options = {}) ⇒ DPD::Response

Patched request handler to include the credentials

Parameters:

  • verb (String)

    the HTTP method.

  • uri (URI)

    the HTTP URI.

  • options (Hash) (defaults to: {})

    the params/json-payload/form to include.

Returns:

  • (DPD::Response)


31
32
33
34
35
# File 'lib/dpd.rb', line 31

def self.request(verb, uri, options = {})
  options[:json] ||= {}
  options[:json].merge!(credentials)
  super(verb, uri, options)
end