Class: Trefoil::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/trefoil/client.rb

Overview

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

Constant Summary collapse

BASE_URL =
'a.4cdn.org'

Instance Method Summary collapse

Constructor Details

#initializeClient

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



14
15
16
17
18
# File 'lib/trefoil/client.rb', line 14

def initialize
  @last_request = Time.now - 1
  @mutex = Mutex.new
  @board_cache = {}
end

Instance Method Details

#board(board_name) ⇒ Object

Get a board object based on its name

Parameters:

  • board_name (String)


43
44
45
# File 'lib/trefoil/client.rb', line 43

def board(board_name)
  Board.new(self, board_name)
end

#get(endpoint) ⇒ Hash<Symbol => String, Fixnum>

Get a JSON parsed response from a given endpoint. Limited to 1 request per second in compliance with API rules.

Parameters:

  • endpoint (String)

    The endpoint to request data from.

Returns:

  • (Hash<Symbol => String, Fixnum>)

    The returned data structure



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 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