class Suretax::Response

Attributes

api[R]
body[R]
response[R]
status[R]

Public Class Methods

new(api_response) click to toggle source
# File lib/suretax/response.rb, line 7
def initialize(api_response)
  @response = api_response
  sanitized_body = remove_xml_brackets(api_response.body)

  if sanitized_body == "invalid request"
    invalid_request_response(sanitized_body)
  else
    valid_request_response(sanitized_body)
  end
end

Public Instance Methods

success?() click to toggle source
# File lib/suretax/response.rb, line 18
def success?
  status == 200
end

Private Instance Methods

configuration() click to toggle source
# File lib/suretax/response.rb, line 74
def configuration
  Suretax.configuration
end
extract_json_from_urlencoded_string_regex() click to toggle source
# File lib/suretax/response.rb, line 42
def extract_json_from_urlencoded_string_regex
  # http://rubular.com/r/0w73fy4Ldk
  /\A<\?xml.*<string[^>]+>(?<json_string>.+)<\/string>\z/m
end
invalid_request_response(sanitized_body) click to toggle source
# File lib/suretax/response.rb, line 34
def invalid_request_response(sanitized_body)
  @body = sanitized_body
  @status = 400
  @api = nil
  log_response
  self
end
log_response() click to toggle source
# File lib/suretax/response.rb, line 66
def log_response
  logger&.debug "\nSureTax Response Received:\n#{@body.inspect}"
end
logger() click to toggle source
# File lib/suretax/response.rb, line 70
def logger
  configuration.logger
end
map_response_code_to_http_status(api_status_code) click to toggle source
# File lib/suretax/response.rb, line 55
def map_response_code_to_http_status(api_status_code)
  case api_status_code
  when "9999"
    200
  when "9001"
    409
  else
    400
  end
end
remove_xml_brackets(response_string) click to toggle source
# File lib/suretax/response.rb, line 47
def remove_xml_brackets(response_string)
  if matches = response_string.match(extract_json_from_urlencoded_string_regex)
    matches["json_string"]
  else
    response_string
  end
end
valid_request_response(sanitized_body) click to toggle source
# File lib/suretax/response.rb, line 24
def valid_request_response(sanitized_body)
  @body = JSON.parse(sanitized_body)
  @api = Api::Response.new(@body)
  @status = map_response_code_to_http_status(api.status)
  log_response
  self
rescue JSON::ParserError => e
  raise(Suretax::Api::ConnectionError, "Failed to parse response from SureTax: #{e.inspect}")
end