Sha256: 77f7802ddac7017dd2f073d4c9e7c1a5492d999f06f77c6ac4d04c78ce96c8a9

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

module Board
  module Request

    class Error < StandardError
      attr_reader :response

      def initialize(response)
        @response = response
      end
    end

    private

    def post(path, params)
      request path, params, :post
    end

    def get(path, params)
      request path, params, :get
    end

    def request(path, params, method)
      params.merge!(:user_credentials => @api_key)

      response = case method
                 when :get
                   uri = URI.parse(@url + path + "?" + hash_to_query_string(params))
                   Net::HTTP.get_response(uri)
                 when :post
                   uri = URI.parse(@url + path)
                   Net::HTTP.post_form(uri, params)
                 end

      if response.code =~ /2../
        Yajl::Parser.parse(response.body)
      else
        raise Error.new(response)
      end
    end

    def hash_to_query_string(hash)
      params = ''
      stack = []

      hash.each do |k, v|
        if v.is_a?(Hash)
          stack << [k,v]
        else
          params << "#{k}=#{v}&"
        end
      end

      stack.each do |parent, hash|
        hash.each do |k, v|
          if v.is_a?(Hash)
            stack << ["#{parent}[#{k}]", v]
          else
            params << "#{parent}[#{k}]=#{v}&"
          end
        end
      end

      params.chop! # trailing &
      params
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
board-client-0.2.0 lib/board/request.rb