Sha256: 7a4b95ffa21e710b312027d1ada8746e7b9b8c7f7f90ff39a85798b8d7c37906

Contents?: true

Size: 1.17 KB

Versions: 18

Compression:

Stored size: 1.17 KB

Contents

# frozen_string_literal: true

module FriendlyShipping
  module Services
    class Ups
      class ParseXMLResponse
        extend Dry::Monads::Result::Mixin
        SUCCESSFUL_RESPONSE_STATUS_CODE = '1'

        class << self
          def call(response_body, expected_root_tag)
            xml = Nokogiri.XML(response_body, &:strict)

            if xml.root.nil? || xml.root.name != expected_root_tag
              Failure('Invalid document')
            end
            if request_successful?(xml)
              Success(xml)
            else
              Failure(error_message(xml))
            end
          rescue Nokogiri::XML::SyntaxError => e
            Failure(e)
          end

          private

          def request_successful?(xml)
            xml.root.at('Response/ResponseStatusCode').text == SUCCESSFUL_RESPONSE_STATUS_CODE
          end

          def error_message(xml)
            status = xml.root.at_xpath('Response/ResponseStatusDescription')&.text
            desc = xml.root.at_xpath('Response/Error/ErrorDescription')&.text
            [status, desc].compact.join(": ").presence || 'UPS could not process the request.'
          end
        end
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
friendly_shipping-0.5.2 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.5.1 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.5 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.14 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.13 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.12 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.11 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.10 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.9 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.8 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.7 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.6 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.5 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.4 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.3 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.2 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.1 lib/friendly_shipping/services/ups/parse_xml_response.rb
friendly_shipping-0.4.0 lib/friendly_shipping/services/ups/parse_xml_response.rb