Sha256: d8d8f33431bee9ec789f0cdbd585f70d67d8ec573c68010518ec283d3c5398bb

Contents?: true

Size: 1.55 KB

Versions: 1

Compression:

Stored size: 1.55 KB

Contents

module BlockScore
  module Connection
    def get(path, params)
      request :get, path, params
    end

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

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

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

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

    private

    def headers
      @headers ||= {
        'Accept' => "application/vnd.blockscore+json;version=#{BlockScore::VERSION.to_i}",
        'User-Agent' => "blockscore-ruby/#{BlockScore::VERSION} (https://github.com/BlockScore/blockscore-ruby)",
        'Content-Type' => 'application/json'
      }
    end

    def request(method, path, params)
      fail NoAPIKeyError, 'No API key was provided.' unless BlockScore.api_key

      begin
        response = execute_request(method, path, params)
      rescue SocketError, Errno::ECONNREFUSED => e
        fail APIConnectionError, e.message
      end

      Response.handle_response(resource, response)
    end

    def execute_request(method, path, params)
      auth = { :username => BlockScore.api_key, :password => '' }

      if method == :get
        path = encode_path_params(path, params)
        params = nil
      else
        params = params.to_json
      end

      options = { :basic_auth => auth, :headers => headers, :body => params }

      HTTParty.send(method, path, options)
    end

    def encode_path_params(path, params)
      encoded = URI.encode_www_form(params)
      [path, encoded].join("?")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
blockscore-4.1.0 lib/blockscore/connection.rb