class Geckoboard::Connection

Attributes

api_key[R]

Public Class Methods

new(api_key) click to toggle source
# File lib/geckoboard/connection.rb, line 5
def initialize(api_key)
  @api_key = api_key
end

Public Instance Methods

delete(path) click to toggle source
# File lib/geckoboard/connection.rb, line 15
def delete(path)
  request = Net::HTTP::Delete.new(path)

  make_request(request)
end
get(path) click to toggle source
# File lib/geckoboard/connection.rb, line 9
def get(path)
  request = Net::HTTP::Get.new(path)

  make_request(request)
end
post(path, body) click to toggle source
# File lib/geckoboard/connection.rb, line 29
def post(path, body)
  request = Net::HTTP::Post.new(path)
  request['Content-Type'] = 'application/json'
  request.body = body

  make_request(request)
end
put(path, body) click to toggle source
# File lib/geckoboard/connection.rb, line 21
def put(path, body)
  request = Net::HTTP::Put.new(path)
  request['Content-Type'] = 'application/json'
  request.body = body

  make_request(request)
end

Private Instance Methods

check_for_errors(response) click to toggle source
# File lib/geckoboard/connection.rb, line 48
def check_for_errors(response)
  return if response.code.to_i < 400

  error_message = extract_error_message(response) ||
    "Server responded with unexpected status code (#{response.code})"

  exception = case response
              when Net::HTTPUnauthorized then UnauthorizedError
              when Net::HTTPConflict     then ConflictError
              when Net::HTTPBadRequest   then BadRequestError
              else UnexpectedStatusError
              end

  raise exception, error_message
end
extract_error_message(response) click to toggle source
# File lib/geckoboard/connection.rb, line 64
def extract_error_message(response)
  return unless response_is_json? response

  JSON.parse(response.body)
    .fetch('error', {})
    .fetch('message', nil)
end
http() click to toggle source
# File lib/geckoboard/connection.rb, line 76
def http
  http = Net::HTTP.new('api.geckoboard.com', 443)
  http.use_ssl = true
  http
end
make_request(request) click to toggle source
# File lib/geckoboard/connection.rb, line 39
def make_request(request)
  request.basic_auth(api_key, '')
  request['User-Agent'] = USER_AGENT

  response = http.request(request)
  check_for_errors(response)
  response
end
response_is_json?(response) click to toggle source
# File lib/geckoboard/connection.rb, line 72
def response_is_json?(response)
  (response['Content-Type'] || '').split(';').first == 'application/json'
end