class Rookout::ComWs::TokenBucket

Public Class Methods

new(limit, interval_seconds, &do_once_when_exhausted) click to toggle source
# 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

Public Instance Methods

exhausted?() click to toggle source
# 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() { || ... } click to toggle source
# 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