Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

We’re showing branches in this repository, but you can also compare across forks.

base fork: sferik/twitter
...
head fork: mathieuravaux/twitter
compare: master
  • 1 commit
  • 4 files changed
  • 0 commit comments
  • 1 contributor
2  lib/twitter/api.rb
View
@@ -1,6 +1,7 @@
require 'twitter/connection'
require 'twitter/request'
require 'twitter/authentication'
+require "twitter/ratelimit_status"
module Twitter
# @private
@@ -19,5 +20,6 @@ def initialize(options={})
include Connection
include Request
include Authentication
+ include RatelimitStatus
end
end
26 lib/twitter/ratelimit_status.rb
View
@@ -0,0 +1,26 @@
+require "hashie"
+require "time"
+
+module Twitter
+ # Reports the rate limit status from response HTTP headers
+ module RatelimitStatus
+
+ def ratelimit_status
+ @ratelimit_status ||= Hashie::Mash.new { |hash, api_class| hash[api_class] = Hashie::Mash.new }
+ end
+
+ def update_ratelimit_status(response)
+ headers = response.headers.select {|k, v| k.include? 'x-ratelimit' }
+ limit_class = headers['x-ratelimit-class']
+
+ status = ratelimit_status[limit_class]
+ response_date = Time.httpdate(response.headers['Date'])
+ return if status.updated_at && status.updated_at > response_date
+
+ status['updated_at'] = response_date
+ headers.each_pair { |k, v| status[k.gsub 'x-ratelimit-', ''] = v.to_i }
+ ratelimit_status[limit_class] = status
+ end
+
+ end
+end
1  lib/twitter/request.rb
View
@@ -34,6 +34,7 @@ def request(method, path, options, raw=false)
request.body = options unless options.empty?
end
end
+ update_ratelimit_status(response)
raw ? response : response.body
end
29 spec/twitter/api_spec.rb
View
@@ -67,4 +67,33 @@
end
end
end
+
+ %w(api api_identified).each do |api_class|
+ context "with requests in API class '#{api_class}'" do
+ before do
+ @client = Twitter::Client.new
+ stub_request(:get, "https://api.twitter.com/statuses/user_timeline.json").
+ with(:query => {:screen_name => 'sferik'}).
+ to_return(:status => 200, :headers => {
+ "Date" => "Sat, 18 Jun 2011 13:55:08 GMT",
+ "x-ratelimit-limit" => "350",
+ "x-ratelimit-remaining" => "22",
+ "x-ratelimit-class" => api_class,
+ "x-ratelimit-reset" => "1308302676",
+ 'x-bogus-header' => 'anything'
+ })
+ end
+
+ it "should report API rate limits from headers" do
+ @client.get('/statuses/user_timeline', {:screen_name => 'sferik'})
+ @client.ratelimit_status[api_class].tap do |rl|
+ rl.updated_at.should eql(Time.parse("2011-06-18 15:55:08 +0200"))
+ rl.remaining.should eql 22
+ rl.limit.should eql 350
+ rl.reset.should eql 1308302676
+ end
+ end
+ end
+ end
+
end

No commit comments for this range

Something went wrong with that request. Please try again.