Class: Redd::RateLimit
- Inherits:
-
Object
- Object
- Redd::RateLimit
- Defined in:
- lib/redd/rate_limit.rb
Overview
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.
Instance Attribute Summary collapse
-
#last_request_time ⇒ Object
readonly
Returns the value of attribute last_request_time.
Instance Method Summary collapse
-
#after_limit { ... } ⇒ Object
Sleep until 2 seconds have passed since the last request and perform the given request.
-
#initialize(gap = 2) ⇒ RateLimit
constructor
A new instance of RateLimit.
Constructor Details
#initialize(gap = 2) ⇒ RateLimit
Returns a new instance of RateLimit.
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_time ⇒ Object (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.
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 |