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
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
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 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 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
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
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
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