Role::Object::RateLimiter - Add a rate limiter to your class
package My::Responder; use Moo; with 'Role::Object::RateLimiter'; # Set up our rate limiter (any time before attempting to use it): has limit_events => ( is => 'ro', required => 1, ); has limit_seconds => ( is => 'ro', required => 1, ); sub BUILD { my ($self) = @_; $self->delayed( events => $self->limit_events, seconds => $self->limit_seconds ); } # do_stuff but only if we're not rate-limited: sub respond { my ($self) = @_; if (my $delay = $self->delayed) { sleep $delay } $self->do_stuff } sub respond_nonblocking { my ($self) = @_; return if $self->delayed; $self->do_stuff }
This is a small role wrapping Object::RateLimiter to make it slightly more convenient to add rate limiting to objects.
Currently only HASH-type objects are supported.
HASH
Although the "SYNOPSIS" uses Moo, this role uses Role::Tiny and can also be composed via Role::Tiny::With.
See Object::RateLimiter for more details.
# Set up the rate limiter: $self->delayed(events => 4, seconds => 5); # Check if this event should be delayed; # returns number of seconds to wait: my $delay = $self->delayed;
If called with arguments, passes them to Object::RateLimiter's constructor and returns the newly initialized rate limiter; any existing rate limiter is replaced.
If called without arguments, records an entry in the Object::RateLimiter's event history and returns the number of seconds until the event should be allowed (or zero if not delayed).
See "delay" in Object::RateLimiter.
Clear the current event history.
Returns the current Object::RateLimiter instance.
Jon Portnoy <avenj@cobaltirc.org>
To install Object::RateLimiter, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Object::RateLimiter
CPAN shell
perl -MCPAN -e shell install Object::RateLimiter
For more information on module installation, please visit the detailed CPAN module installation guide.