Last active
December 31, 2015 01:19
-
-
Save icydee/7913720 to your computer and use it in GitHub Desktop.
Redis as a Moose Attribute
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
package RedisTest; | |
use Moose; | |
use Redis; | |
use namespace::autoclean; | |
has 'id' => ( | |
is => 'ro', | |
default => '945', | |
); | |
has 'redis' => ( | |
is => 'ro', | |
lazy => 1, | |
builder => '_build_redis', | |
); | |
has 'thing' => ( | |
is => 'rw', | |
lazy => 1, | |
builder => '_build_thing', | |
trigger => \&_trigger_thing, | |
); | |
sub _trigger_thing { | |
my ($self, $arg, $old_arg) = @_; | |
print STDERR "IN TRIGGER_THING\n"; | |
$self->redis->set( "test:".$self->id => $arg ); | |
} | |
package RedisTest; | |
use Moose; | |
use Redis; | |
use namespace::autoclean; | |
has 'id' => ( | |
is => 'ro', | |
default => '945', | |
); | |
has 'redis' => ( | |
is => 'ro', | |
lazy => 1, | |
builder => '_build_redis', | |
); | |
has 'thing' => ( | |
is => 'rw', | |
lazy => 1, | |
builder => '_build_thing', | |
trigger => \&_trigger_thing, | |
); | |
sub _trigger_thing { | |
my ($self, $arg, $old_arg) = @_; | |
print STDERR "IN TRIGGER_THING\n"; | |
$self->redis->set( "test:".$self->id => $arg ); | |
} | |
sub _build_thing { | |
my ($self) = @_; | |
print STDERR "IN BUILD_THING\n"; | |
$self->redis->del( "test:".$self->id); | |
return undef; | |
} | |
sub _build_redis { | |
my ($self) = @_; | |
print STDERR "IN BUILD_REDIS\n"; | |
my $redis = Redis->new(server => '127.0.0.1:6379', encoding => undef); | |
return $redis; | |
} | |
around 'thing' => sub { | |
my $orig = shift; | |
my $self = shift; | |
print STDERR "IN AROUND THING\n"; | |
if (@_) { | |
$self->redis->set("test:".$self->id => $_[0]); | |
return $self->$orig($_[0]); | |
} | |
$self->$orig(); | |
return $self->redis->get("test:".$self->id); | |
}; | |
__PACKAGE__->meta->make_immutable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment