Refactoring Github::RateLimit

This commit is contained in:
Douglas Barbosa Alexandre 2017-04-24 19:49:17 -03:00
parent f73a0280c9
commit 275f00ee88
2 changed files with 14 additions and 27 deletions

View file

@ -1,17 +1,19 @@
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

View file

@ -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
# GitHub Rate Limit API returns 404 when the rate limit is disabled
return false unless response.status != 404
def remaining
@remaining ||= body.dig('rate', 'remaining').to_i
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
def reset_in
@reset ||= body.dig('rate', 'reset').to_i
end
private
def response
connection.get(RATE_LIMIT_URL)
end
def body
@body ||= Oj.load(response.body, class_cache: false, mode: :compat)
end
# GitHub Rate Limit API returns 404 when the rate limit is disabled
def enabled?
response.status != 404
[exceed, reset_in]
end
end
end