Refactoring Github::RateLimit

parent f73a0280
module Github
class Client
attr_reader :connection
attr_reader :connection, :rate_limit
def initialize(options)
@connection = Faraday.new(url: options.fetch(:url)) do |faraday|
faraday.authorization 'token', options.fetch(:token)
faraday.adapter :net_http
end
@rate_limit = RateLimit.new(connection)
end
def get(url, query = {})
rate_limit = RateLimit.new(connection)
sleep rate_limit.reset_in if rate_limit.exceed?
exceed, reset_in = rate_limit.get
sleep reset_in if exceed
Github::Response.new(connection.get(url, query))
end
......
......@@ -10,33 +10,18 @@ module Github
@connection = connection
end
def exceed?
return false unless enabled?
def get
response = connection.get(RATE_LIMIT_URL)
remaining <= SAFE_REMAINING_REQUESTS
end
def remaining
@remaining ||= body.dig('rate', 'remaining').to_i
end
def reset_in
@reset ||= body.dig('rate', 'reset').to_i
end
# GitHub Rate Limit API returns 404 when the rate limit is disabled
return false unless response.status != 404
private
def response
connection.get(RATE_LIMIT_URL)
end
def body
@body ||= Oj.load(response.body, class_cache: false, mode: :compat)
end
body = Oj.load(response.body, class_cache: false, mode: :compat)
remaining = body.dig('rate', 'remaining').to_i
reset_in = body.dig('rate', 'reset').to_i
exceed = remaining <= SAFE_REMAINING_REQUESTS
# GitHub Rate Limit API returns 404 when the rate limit is disabled
def enabled?
response.status != 404
[exceed, reset_in]
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment