Sha256: 7fde46d7dbe91485d487cd1bc0bd16b4e0f00e7a9a806dd87049c87bec0bef9c

Contents?: true

Size: 1.85 KB

Versions: 2

Compression:

Stored size: 1.85 KB

Contents

module RemoteResource
  class Response

    attr_reader :original_response, :original_request
    private :original_response, :original_request

    def initialize(response, connection_options = {})
      @original_response  = response
      @original_request   = response.request
      @connection_options = connection_options
    end

    def success?
      original_response.success?
    end

    def unprocessable_entity?
      response_code == 422
    end

    def response_body
      original_response.body
    end

    def response_code
      original_response.response_code
    end

    def response_headers
      original_response.headers
    end

    def sanitized_response_body
      return empty_hash if response_body.blank?
      return empty_hash if parsed_response_body.blank?

      unpacked_parsed_response_body
    end

    def sanitized_response_meta
      return empty_hash if response_body.blank?
      return empty_hash if parsed_response_body.blank?

      return parsed_response_body['meta'] if parsed_response_body.try :has_key?, 'meta'

      empty_hash
    end

    def error_messages_response_body
      return empty_hash if response_body.blank?
      return empty_hash if parsed_response_body.blank?

      return parsed_response_body["errors"]          if parsed_response_body.try :has_key?, "errors"
      return unpacked_parsed_response_body["errors"] if unpacked_parsed_response_body.try :has_key?, "errors"

      empty_hash
    end

    def parsed_response_body
      @parsed_response_body ||= JSON.parse response_body
    rescue JSON::ParserError
      nil
    end

    private

    def empty_hash
      {}
    end

    def unpacked_parsed_response_body
      root_element = @connection_options[:root_element].presence

      if root_element
        parsed_response_body[root_element.to_s]
      else
        parsed_response_body
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ddy_remote_resource-1.0.0.rc2 lib/remote_resource/response.rb
ddy_remote_resource-1.0.0.rc1 lib/remote_resource/response.rb