class Trefoil::Client

Client used for making requests to the API. Respects API rules for rate limiting and thread watching.

Constants

BASE_URL

Public Class Methods

new() click to toggle source

Initialize with a last_request time 1 second prior to present so that we can make requests right away

# File lib/trefoil/client.rb, line 14
def initialize
  @last_request = Time.now - 1
  @mutex = Mutex.new
  @board_cache = {}
end

Public Instance Methods

board(board_name) click to toggle source

Get a board object based on its name @param board_name [String]

# File lib/trefoil/client.rb, line 43
def board(board_name)
  Board.new(self, board_name)
end
get(endpoint) click to toggle source

Get a JSON parsed response from a given endpoint. Limited to 1 request per second in compliance with API rules. @param endpoint [String] The endpoint to request data from. @return [Hash<Symbol => String, Fixnum>] The returned data structure

# File lib/trefoil/client.rb, line 24
def get(endpoint)
  @mutex.synchronize do
    sleep time_until_available if must_wait?
    resp = Net::HTTP.get_response(BASE_URL, format_endpoint(endpoint))
    @last_request = Time.now
    case resp.code.to_i
    when 200
      JSON.parse(resp.body, symbolize_names: true)
    when 400..500
      raise 'Error making a request' # TODO: Better error handling
    else
      p endpoint
      raise 'Unhandled status code' # TODO: better code handling
    end
  end
end

Private Instance Methods

cache_boards() click to toggle source

Cache boards from `/boards.json`. Called when accessing `Board#[]` for the first time. Effects last request time.

# File lib/trefoil/client.rb, line 72
def cache_boards
  boards = get('boards.json')
  boards[:boards].each do |board_obj|
    @board_cache[board_obj[:board]] = board_obj
  end

  @board_cache[:troll_flags] = boards[:troll_flags]
end
format_endpoint(endpoint) click to toggle source

Adds leading '/' to requests @param endpoint [String] The endpoint being formatted @return [String] `endpoint` with leading `/` added if needed

# File lib/trefoil/client.rb, line 52
def format_endpoint(endpoint)
  return endpoint if endpoint[0] == '/'

  '/' + endpoint
end
must_wait?() click to toggle source

Whether we must wait to make a request @return [true, false] Whether we need to wait or not

# File lib/trefoil/client.rb, line 66
def must_wait?
  time_until_available.positive?
end
time_until_available() click to toggle source

Amount of time before the mutex is freed for the next request @return [Fixnum, Float] Time remaining until the next request can be made

# File lib/trefoil/client.rb, line 60
def time_until_available
  (@last_request + 1) - Time.now
end