Skip to content

Commit

Permalink
Throw rate limit exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenRoos committed Mar 21, 2012
1 parent c21dc6c commit 5cf024d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
3 changes: 3 additions & 0 deletions lib/blue_jay/exceptions/rate_limit_exception.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

class RateLimitException < Exception
end
32 changes: 22 additions & 10 deletions lib/blue_jay/response.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@

require 'blue_jay/exceptions/rate_limit_exception'

module BlueJay
class Response

RATE_LIMIT_HEADER ="X-RateLimit-Limit"
RATE_LIMIT_REMAINING_HEADER = "X-RateLimit-Remaining"
RATE_LIMIT_RESET_HEADER = "X-RateLimit-Reset"

def initialize(response, debug = false)
parse_response(response, debug)
def initialize(response, options={})
@raw_data = options[:raw_data]
@debug = options[:debug]
parse_response(response)
end

def successful?; @success end
Expand All @@ -20,27 +25,25 @@ def rate_limit_reset_time; @rate_limit_reset_time end

private

def parse_response(response, debug)
def parse_response(response)
@success = false
@data = nil
@error = nil

puts "BlueJay => #{response.inspect}" if debug
puts "BlueJay => #{response.inspect}" if @debug

# handle the case of the empty or missing response...
return if response.nil? || !response.kind_of?(Net::HTTPResponse)

@status = response.class
@rate_limit = response[RATE_LIMIT_HEADER]
@rate_limit_remaining = response[RATE_LIMIT_REMAINING_HEADER]

reset_time_ticks = response[RATE_LIMIT_RESET_HEADER]
@rate_limit_reset_time = (reset_time_ticks) ? Time.at(reset_time_ticks.to_i) : nil
get_rate_limit_info(response)
raise RateLimitException if rate_limited?

begin

# try to parse the response as JSON...
@data = JSON.parse(response.body)
# try to parse the response as JSON (unless @raw_data)...
@data = (@raw_data) ? response.body : JSON.parse(response.body)

# errors can be detected by the status code (not Success) or
# by the presence of an "error" object in the de-serialized response...
Expand All @@ -52,9 +55,18 @@ def parse_response(response, debug)
# a json response anyway that gives us information
# about the response in a well structured manner...
@data = response.body
@success = false
@error = e
end
end

def get_rate_limit_info(response)
reset_time_ticks = response[RATE_LIMIT_RESET_HEADER]

@rate_limit = response[RATE_LIMIT_HEADER]
@rate_limit_remaining = response[RATE_LIMIT_REMAINING_HEADER]
@rate_limit_reset_time = (reset_time_ticks) ? Time.at(reset_time_ticks.to_i) : nil
end

end
end

0 comments on commit 5cf024d

Please sign in to comment.