Class: Redd::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/redd/rate_limit.rb

Overview

Note:

The class itself doesn’t perform the rate limiting but only acts as an updatable container for the values.

The class that handles rate limiting for reddit. reddit does supply X-Ratelimit headers but only when logged in and using those headers instead would just lead to short bursts, so it’s better to go at a constant speed and space out requests every 2 seconds.

If you’d rather have short bursts or no rate limiting at all, it’s easy to write one yourself. A rate limiting class is any class that has an #after_limit method. The block returns a Faraday::Response object, so you can also extract the headers from the response and use those instead. To remove rate limiting entirely, follow the example below.

Examples:

No Rate Limiting

class IWantToGetIPBanned
  def after_limit
    yield
  end
end

client = Redd::Unauthenticated.new(rate_limit: IWantToGetIPBanned.new)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(gap = 2) ⇒ RateLimit

Returns a new instance of RateLimit.

Parameters:

  • gap (Float, Integer) (defaults to: 2)

    The minimum time between each request.



30
31
32
33
34
# File 'lib/redd/rate_limit.rb', line 30

def initialize(gap = 2)
  # Some time ages ago, because we never made a request.
  @last_request_time = Time.at(0)
  @gap = gap
end

Instance Attribute Details

#last_request_timeObject (readonly)

Returns the value of attribute last_request_time.



27
28
29
# File 'lib/redd/rate_limit.rb', line 27

def last_request_time
  @last_request_time
end

Instance Method Details

#after_limit { ... } ⇒ Object

Sleep until 2 seconds have passed since the last request and perform the given request.

Yields:

  • A block.

Returns:

  • The return value of the block.



41
42
43
44
45
46
47
# File 'lib/redd/rate_limit.rb', line 41

def after_limit
  seconds_passed = Time.now - @last_request_time
  wait_time = @gap - seconds_passed
  sleep(wait_time) if wait_time > 0
  @last_request_time = Time.now
  yield
end