Sha256: f64dc4805f57a363c27e2ecc1c1c1f7c6d2c3ccdd14cacd8146ad31b1a5d8f9f

Contents?: true

Size: 1.47 KB

Versions: 14

Compression:

Stored size: 1.47 KB

Contents

module DwollaSwagger
  module Swagger
    class Response
      require 'json'

      attr_accessor :raw

      def initialize(raw)
        self.raw = raw

        case self.code
        when 500..510 then raise(ServerError, self.error_message)
        when 299..426 then raise(ClientError, self.error_message)
        end
      end

      def code
        raw.code
      end

      # Account for error messages that take different forms...
      def error_message
        body['message']
      rescue
        body
      end

      # If body is JSON, parse it
      # Otherwise return raw string
      def body
        JSON.parse(raw.body, :symbolize_names => true)
      rescue
        raw.body
      end

      # `headers_hash` is a Typhoeus-specific extension of Hash,
      # so simplify it back into a regular old Hash.
      def headers
        h = {}
        raw.headers_hash.each {|k,v| h[k] = v }
        h
      end

      # Extract the response format from the header hash
      # e.g. {'Content-Type' => 'application/json'}
      def format
        headers['Content-Type'].split("/").last.downcase
      end

      def json?
        format == 'json'
      end

      def xml?
        format == 'xml'
      end

      def pretty_body
        return unless body.present?
        case format
        when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
        end
      end

      def pretty_headers
        JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
dwolla_swagger-1.0.13 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.12 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.11 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.10 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.9 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.8 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.7 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.6 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.5 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.4 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.3 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.2 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.1 lib/dwolla_swagger/swagger/response.rb
dwolla_swagger-1.0.0 lib/dwolla_swagger/swagger/response.rb