Skip to content

Instantly share code, notes, and snippets.

@rsrchboy
Created May 19, 2012 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsrchboy/2729554 to your computer and use it in GitHub Desktop.
Save rsrchboy/2729554 to your computer and use it in GitHub Desktop.
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