Class: Redd::RateLimit

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

Overview

The class that handles rate limiting for reddit.

If you’d rather have an asynchronous or queue-based limiting, 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:

To remove rate limiting entirely, just burst forever.

rt = Redd::RateLimit.new
rt.burst!(Float::INFINITY)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(gap) ⇒ RateLimit



34
35
36
37
38
39
# File 'lib/redd/rate_limit.rb', line 34

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

Instance Attribute Details

#burst_lengthInteger



21
22
23
# File 'lib/redd/rate_limit.rb', line 21

def burst_length
  @burst_length
end

#gapInteger, Float



17
18
19
# File 'lib/redd/rate_limit.rb', line 17

def gap
  @gap
end

#last_requestTime (readonly)



25
26
27
# File 'lib/redd/rate_limit.rb', line 25

def last_request
  @last_request
end

#remainingInteger (readonly)



31
# File 'lib/redd/rate_limit.rb', line 31

attr_reader :used, :remaining, :reset

#resetInteger (readonly)



31
# File 'lib/redd/rate_limit.rb', line 31

attr_reader :used, :remaining, :reset

#usedInteger (readonly)



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

def used
  @used
end

Instance Method Details

#after_limit {|Faraday::Response| ... } ⇒ Faraday::Response

Sleep until 1 second has passed since the last request and perform the given request unless bursting.

Yields:

  • (Faraday::Response)

    A response.



53
54
55
56
57
58
# File 'lib/redd/rate_limit.rb', line 53

def after_limit
  response = yield
  update!(response)
  sleep(wait_time)
  response
end

#burst!(times) ⇒ Integer

Don’t sleep for the next few requests.



44
45
46
# File 'lib/redd/rate_limit.rb', line 44

def burst!(times)
  @burst_length += times
end