Class: Vines::TokenBucket
- Inherits:
-
Object
- Object
- Vines::TokenBucket
- Defined in:
- lib/vines/token_bucket.rb
Overview
The token bucket algorithm is useful for rate limiting. Before an operation can be completed, a token is taken from the bucket. If no tokens are available, the operation fails. The bucket is refilled with tokens at the maximum allowed rate of operations.
Instance Method Summary collapse
-
#initialize(capacity, rate) ⇒ TokenBucket
constructor
Create a full bucket with capacity number of tokens to be filled at the given rate of tokens/second.
-
#take(tokens) ⇒ Object
Returns true if tokens can be taken from the bucket.
Constructor Details
#initialize(capacity, rate) ⇒ TokenBucket
Create a full bucket with capacity number of tokens to be filled at the given rate of tokens/second.
14 15 16 17 18 19 20 21 |
# File 'lib/vines/token_bucket.rb', line 14 def initialize(capacity, rate) raise ArgumentError.new('capacity must be > 0') unless capacity > 0 raise ArgumentError.new('rate must be > 0') unless rate > 0 @capacity = capacity @tokens = capacity @rate = rate @timestamp = Time.new end |
Instance Method Details
#take(tokens) ⇒ Object
Returns true if tokens can be taken from the bucket.
24 25 26 27 28 29 30 31 32 |
# File 'lib/vines/token_bucket.rb', line 24 def take(tokens) raise ArgumentError.new('tokens must be > 0') unless tokens > 0 if tokens <= fill @tokens -= tokens true else false end end |