Sha256: ba9cc5407d22c2806cbb7539108ea9e80607a3e1e3e837ca94abb17746d101b3

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

module Aitch
  class Response
    extend Forwardable

    def_delegators :@http_response, :content_type

    def initialize(http_response)
      @http_response = http_response
    end

    def code
      @http_response.code.to_i
    end

    def body
      @body ||= Body.new(@http_response).to_s
    end

    def success?
      code >= 200 && code <= 399
    end

    def redirect?
      code >= 300 && code <= 399
    end

    def error?
      code >= 400 && code <= 599
    end

    def error
      error? && ERRORS.fetch(code)
    end

    def json?
      content_type =~ /json/
    end

    def xml?
      content_type =~ /xml/
    end

    def html?
      content_type =~ /html/
    end

    def data
      if json?
        Aitch.configuration.json_parser.load(body)
      elsif xml?
        Aitch.configuration.xml_parser.load(body)
      else
        body
      end
    end

    def headers
      @headers ||= {}.tap do |headers|
        @http_response.each_header do |name, value|
          headers[name.gsub(/^x-/, "")] = value
        end
      end
    end

    def method_missing(name, *args, &block)
      return headers[name.to_s] if headers.key?(name.to_s)
      super
    end

    def respond_to_missing?(name, include_private = false)
      headers.key?(name.to_s)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
aitch-0.1.0 lib/aitch/response.rb