Class: RailsThrottle::Throttle
- Inherits:
-
Object
- Object
- RailsThrottle::Throttle
- Defined in:
- lib/rails_throttle/throttle.rb
Class Method Summary collapse
-
.decrement(key, options = {}) ⇒ Integer
Decrements the counter for a given key.
-
.increment(key, options = {}) {|key, value| ... } ⇒ Integer
Increments the counter for a given key.
-
.reset(key) ⇒ Object
Resets a key so that it is no longer throttled.
-
.throttled?(key, options = {}) ⇒ Boolean
Returns true if the key is throttled, false otherwise.
Class Method Details
.decrement(key, options = {}) ⇒ Integer
Decrements the counter for a given key.
61 62 63 64 65 66 67 68 69 70 |
# File 'lib/rails_throttle/throttle.rb', line 61 def self.decrement(key, = {}) raise "Key cannot be blank." if key.blank? decrement = [:decrement] || 1 period = [:period] raise "Must specify :period in the parameters" if period.nil? RailsThrottle.backend.decrement(key, decrement, expires_in: period) end |
.increment(key, options = {}) {|key, value| ... } ⇒ Integer
Increments the counter for a given key.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/rails_throttle/throttle.rb', line 17 def self.increment(key, = {}, &block) raise "Key cannot be blank" if key.blank? increment = [:increment] || 1 limit = [:limit] period = [:period] raise "Must specify :limit in the parameters" if limit.nil? raise "Must specify :period in the parameters" if period.nil? value = RailsThrottle.backend.increment(key, increment, expires_in: period) if value.nil? RailsThrottle.backend.write(key, increment, expires_in: period) value = increment end if value > limit RailsThrottle.backend.decrement(key, increment, expires_in: period) raise RailsThrottle::ThrottleError, "Limit exceeded for key `#{key}` with limit of #{limit}" end unless block.nil? if block.arity.zero? block.call elsif block.arity == 1 block.call(key) else block.call(key, value) end else value end end |
.reset(key) ⇒ Object
Resets a key so that it is no longer throttled.
94 95 96 97 98 |
# File 'lib/rails_throttle/throttle.rb', line 94 def self.reset(key) raise "Key cannot be blank." if key.blank? RailsThrottle.backend.delete(key) end |
.throttled?(key, options = {}) ⇒ Boolean
Returns true if the key is throttled, false otherwise.
79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/rails_throttle/throttle.rb', line 79 def self.throttled?(key, = {}) raise "Key cannot be blank." if key.blank? limit = [:limit] raise "Must specify :limit in the parameters" if limit.nil? value = RailsThrottle.backend.read(key) || 0 value >= limit end |