Sha256: 6b0e5af8ddc01656527eb0d3a89d38040d6133d0e981069a850012baf30455fc

Contents?: true

Size: 1.01 KB

Versions: 3

Compression:

Stored size: 1.01 KB

Contents

module Buildbox
  class Response
    attr_reader :payload

    def initialize(response)
      @response = response

      unless success?
        raise "API Error: #{@response.code} #{@response.body}"
      end

      if json?
        json = JSON.parse(@response.body)

        if json.kind_of?(Array)
          @payload = json.map { |item| symbolize_keys(item) }
        else
          @payload = symbolize_keys(json)
        end
      end
    end

    def success?
      @response.code.to_i == 200
    end

    private

    def json?
      @response['content-type'] =~ /json/
    end

    def symbolize_keys(hash)
      hash.inject({}) do |result, item|
        key, value = item
        new_key   = case key
                    when String then key.to_sym
                    else key
                    end
        new_value = case value
                    when Hash then symbolize_keys(value)
                    else value
                    end
        result[new_key] = new_value
        result
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
buildbox-0.0.4 lib/buildbox/response.rb
buildbox-0.0.3 lib/buildbox/response.rb
buildbox-0.0.2 lib/buildbox/response.rb