Class: Chokepoint::Interval
- Defined in:
- lib/chokepoint/interval.rb
Overview
This rate limiter strategy throttles the block by enforcing a minimum interval (by default, 1 second) between subsequent allowed calls.
Instance Attribute Summary
Attributes inherited from Limiter
Instance Method Summary collapse
-
#allowed?(context) ⇒ Boolean
Returns ‘true` if sufficient time (equal to or more than #minimum_interval) has passed since the last call.
-
#initialize(name, options = {}) ⇒ Interval
constructor
A new instance of Interval.
-
#minimum_interval ⇒ Float
Returns the required minimal interval (in terms of seconds) that must elapse between two subsequent calls.
Methods inherited from Limiter
#blacklisted?, #throttle, #whitelisted?
Constructor Details
#initialize(name, options = {}) ⇒ Interval
Returns a new instance of Interval.
17 18 19 |
# File 'lib/chokepoint/interval.rb', line 17 def initialize(name, = {}) super end |
Instance Method Details
#allowed?(context) ⇒ Boolean
Returns ‘true` if sufficient time (equal to or more than #minimum_interval) has passed since the last call.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/chokepoint/interval.rb', line 27 def allowed?(context) time_now = Time.now.to_f last_call_time = cache_get(key = cache_key(context)) rescue nil allowed = !last_call_time || (dt = time_now - last_call_time.to_f) >= minimum_interval begin cache_set(key, time_now) allowed rescue => e # If an error occurred while trying to update the timestamp stored # in the cache, we will fall back to allowing the request through. # This prevents the application blowing up merely due to a # backend cache server (Memcached, Redis, etc.) being offline. allowed = true end end |
#minimum_interval ⇒ Float
Returns the required minimal interval (in terms of seconds) that must elapse between two subsequent calls.
48 49 50 |
# File 'lib/chokepoint/interval.rb', line 48 def minimum_interval @min ||= (@options[:min] || 1.0).to_f end |