Create a gist now

Instantly share code, notes, and snippets.

Cheap caching with AutoDestruct
# ta-da!
has expensive_value => (is => 'ro', lazy_build => 1);
sub _build_foo { ... something expensive ... }
has expensive_value => (is => 'ro', lazy_build => 1);
sub _build_foo { ... something expensive ... }
has ev_birthday => (is => 'rw', clearer => 'clear_ev_birthday');
after _build_foo => sub { shift->ev_birthday(time()) };
before expensive_value => sub {
my $self = shift @_;
$self->clear_expensive_value
if time() - $self->ev_birthday > 55*60; # 55 minutes, in seconds
};
has expensive_value => (
traits => [AutoDestruct],
is => 'ro',
lazy_build => 1,
ttl => 55*60, # seconds
);
sub _build_foo { ... something expensive ... }
# somewhere else in your code, on an instance $foo
my $value = $foo->expensive_value; # first call, value generated!
# 30 minutes later
my $value = $foo->expensive_value; # time delta < ttl value; stored value used
# 30 minutes after that
my $value = $foo->expensive_value; # too old! value cleared; normal lazy gen follows
# 30 minutes after that
my $value = $foo->expensive_value; # too old! value cleared; normal lazy gen follows
# essentially:
my $value = do {
$foo->clear_expensive_value
if time() - $foo->ev_birthday > 55*60;
$foo->expensive_value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment