Redis::Hash tie with optional prefix
authorDobrica Pavlinusic <dpavlin@rot13.org>
Sun, 22 Mar 2009 19:17:51 +0000 (19:17 +0000)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Sun, 22 Mar 2009 19:17:51 +0000 (19:17 +0000)
git-svn-id: svn+ssh://llin/home/dpavlin/private/svn/Redis@42 447b33ff-793d-4489-8442-9bea7d161be5

lib/Redis/Hash.pm [new file with mode: 0644]
t/20-Redis-Hash.t [new file with mode: 0755]

diff --git a/lib/Redis/Hash.pm b/lib/Redis/Hash.pm
new file mode 100644 (file)
index 0000000..6dad3dc
--- /dev/null
@@ -0,0 +1,63 @@
+package Redis::Hash;
+
+use strict;
+use warnings;
+
+use Tie::Hash;
+use base qw/Redis Tie::StdHash/;
+
+=head1 NAME
+
+Redis::Hash - tie perl hashes into Redis
+
+=head1 SYNOPSYS
+
+  tie %$name, 'Redis::Hash', 'name';
+
+=cut
+
+# mandatory methods
+sub TIEHASH {
+       my ($class,$name) = @_;
+       my $self = $class->new;
+       $self->{name} = $name || '';
+       bless $self => $class;
+}
+
+sub STORE {
+       my ($self,$key,$value) = @_;
+       $self->set( $self->{name} . $key, $value );
+}
+
+sub FETCH {
+       my ($self,$key) = @_;
+       $self->get( $self->{name} . $key );
+}
+
+sub FIRSTKEY {
+       my $self = shift;
+       $self->{keys} = [ $self->keys( $self->{name} . '*') ];
+       unshift @{ $self->{keys} };
+} 
+
+sub NEXTKEY {
+       my $self = shift;
+       unshift @{ $self->{keys} };
+}
+
+sub EXISTS {
+       my ($self,$key) = @_;
+       $self->exists( $self->{name} . $key );
+}
+
+sub DELETE {
+       my ($self,$key) = @_;
+       $self->del( $self->{name} . $key );
+}
+
+sub CLEAR {
+       my ($self) = @_;
+       $self->del( $_ ) foreach ( $self->keys( $self->{name} . '*' ) );
+}
+
+1;
diff --git a/t/20-Redis-Hash.t b/t/20-Redis-Hash.t
new file mode 100755 (executable)
index 0000000..4bef8a5
--- /dev/null
@@ -0,0 +1,30 @@
+#!/usr/bin/perl
+
+use warnings;
+use strict;
+
+use Test::More tests => 7;
+use lib 'lib';
+use Data::Dump qw/dump/;
+
+BEGIN {
+       use_ok( 'Redis::Hash' );
+}
+
+my $h;
+
+ok( my $o = tie( %$h, 'Redis::Hash', 'test-redis-hash' ), 'tie' );
+
+isa_ok( $o, 'Redis::Hash' );
+
+$h = {};
+
+ok( ! %$h, 'empty' );
+
+ok( $h = { 'foo' => 42, 'bar' => 1, 'baz' => 99 }, '=' );
+
+is_deeply( $h, { bar => 1, baz => 99, foo => 42 }, 'values' );
+
+is_deeply( [ keys %$h ], [ 'bar', 'baz', 'foo' ], 'keys' );
+
+diag dump( $h );