Class: Rookout::ComWs::TokenBucket
- Inherits:
-
Object
- Object
- Rookout::ComWs::TokenBucket
- Defined in:
- lib/rookout/com_ws/token_bucket.rb
Instance Method Summary collapse
- #exhausted? ⇒ Boolean
- #if_available ⇒ Object
-
#initialize(limit, interval_seconds, &do_once_when_exhausted) ⇒ TokenBucket
constructor
A new instance of TokenBucket.
Constructor Details
#initialize(limit, interval_seconds, &do_once_when_exhausted) ⇒ TokenBucket
Returns a new instance of TokenBucket.
4 5 6 7 8 9 10 11 |
# File 'lib/rookout/com_ws/token_bucket.rb', line 4 def initialize limit, interval_seconds, &do_once_when_exhausted @initial_limit = limit @remaining = limit @last_reset = Time.new @interval = interval_seconds @do_once_when_exhausted = do_once_when_exhausted @do_once_when_exhausted_performed = false end |
Instance Method Details
#exhausted? ⇒ Boolean
13 14 15 16 17 18 19 20 21 |
# File 'lib/rookout/com_ws/token_bucket.rb', line 13 def exhausted? if Time.new - @last_reset > @interval @last_reset = Time.new @remaining = @initial_limit @do_once_when_exhausted_performed = false end @remaining < 0 end |
#if_available ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/rookout/com_ws/token_bucket.rb', line 23 def if_available @remaining -= 1 if exhausted? return if @do_once_when_exhausted_performed || @do_once_when_exhausted.nil? @do_once_when_exhausted.call @do_once_when_exhausted_performed = true else yield end end |