Rate limit instance methods using Limiter::Mixin
mainYou can rate limit instance methods by extending Limiter::Mixin in your class and using the limit_method macro.
By default, the rate is defined as the number of requests per minute. When the rate is exceeded, calls to the method will block until the rate limit allows for another execution.
Key parameters:
rate: The maximum number of calls allowed within the interval.interval: The throttling period in seconds (defaults to 60 seconds/1 minute).balanced: A boolean. Iftrue, calls are interleaved (e.g., one call every second) instead of bursting all calls at once at the start of the interval.
class Widget
extend Limiter::Mixin
# Limit to 300 calls per minute
limit_method :tick, rate: 300
# Limit to 5 calls per second and execute a block when the limit is reached
limit_method(:tick, rate: 5, interval: 1) do
puts 'Limit reached'
end
# Evenly distribute 60 calls over 60 seconds
limit_method :tick, rate: 60, balanced: true
end