Created
May 19, 2012 06:09
-
-
Save rsrchboy/2729554 to your computer and use it in GitHub Desktop.
Cheap caching with AutoDestruct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ta-da! | |
has expensive_value => (is => 'ro', lazy_build => 1); | |
sub _build_foo { ... something expensive ... } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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