Skip to content

Commit

Permalink
Apply rate limiting PR from avidw (samsymons#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
Marty Dill authored and Marty Dill committed Oct 16, 2014
1 parent 91787b5 commit ea99451
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ subreddits = client.subscribed_subreddits

Using RedditKit.rb at the module level allows you to use a single account without having to keep track of RedditKit::Client instances. Working at the instance method level makes it possible to use multiple accounts at once, with one client object per account.

> RedditKit.rb doesn't have any built-in rate limiting. reddit's API rules require that you make no more than 30 requests per minute and try to avoid requesting the same page more than once every 30 seconds. You can read up on the API rules [on their wiki page](https://github.com/reddit/reddit/wiki/API).
### Authentication

```ruby
Expand Down
8 changes: 8 additions & 0 deletions lib/redditkit/client.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
require 'faraday'
require 'redditkit/error'
require 'redditkit/version'
require 'redditkit/rate_limit'
require 'redditkit/client/account'
require 'redditkit/client/apps'
require 'redditkit/client/captcha'
Expand Down Expand Up @@ -50,6 +51,7 @@ class Client
attr_accessor :authentication_endpoint
attr_accessor :user_agent
attr_accessor :middleware
attr_accessor :rate_limit

def initialize(username = nil, password = nil)
@username = username
Expand Down Expand Up @@ -84,6 +86,10 @@ def middleware

private

def rate_limit
@rate_limit ||= RedditKit::RateLimit.new
end

def get(path, params = nil)
request(:get, path, params, connection)
end
Expand All @@ -105,6 +111,8 @@ def delete_path(path, params = nil)
end

def request(method, path, parameters = {}, request_connection)
rate_limit.wait

if signed_in?
request = authenticated_request_configuration(method, path, parameters)
request_connection.send(method.to_sym, path, parameters, &request).env
Expand Down
19 changes: 19 additions & 0 deletions lib/redditkit/rate_limit.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module RedditKit

# The class to rate-limit requests to reddit.
class RateLimit
# Time the last request was made.
attr_reader :last_request

def initialize
@last_request = Time.at(0)
end

# Sleep until a given number of seconds have passed since the last request
def wait(gap = 2)
wait_time = @last_request + gap - Time.now
sleep(wait_time) if wait_time > 0
@last_request = Time.now
end
end
end

0 comments on commit ea99451

Please sign in to comment.