MooseX-Storage
view release on metacpan or search on metacpan
t/103_io_storable_file_custom.t view on Meta::CPAN
use strict;
use warnings;
use Test::More tests => 14;
use Test::Deep;
use Storable ();
use File::Temp qw(tempdir);
use File::Spec::Functions;
my $dir = tempdir( CLEANUP => 1 );
{
package Foo;
use Moose;
use MooseX::Storage;
with Storage(io => 'StorableFile');
has 'unset' => ( is => 'ro', isa => 'Any' );
has 'undef' => ( is => 'ro', isa => 'Any' );
has 'number' => (is => 'ro', isa => 'Int');
has 'string' => (is => 'rw', isa => 'Str');
has 'float' => (is => 'ro', isa => 'Num');
has 'array' => (is => 'ro', isa => 'ArrayRef');
has 'hash' => (is => 'ro', isa => 'HashRef');
has 'object' => (is => 'ro', isa => 'Object');
## add some custom freeze/thaw hooks here ...
sub thaw {
my ( $class, $data ) = @_;
my $self = $class->unpack( $data );
$self->string("Hello World");
$self;
}
sub freeze {
my ( $self, @args ) = @_;
my $data = $self->pack(@args);
$data->{string} = "HELLO WORLD";
$data;
}
}
my $file = catfile($dir,'temp.storable');
{
my $foo = Foo->new(
undef => undef,
number => 10,
string => 'foo',
float => 10.5,
array => [ 1 .. 10 ],
hash => { map { $_ => undef } (1 .. 10) },
object => Foo->new( number => 2 ),
);
isa_ok($foo, 'Foo');
$foo->store($file);
# check our custom freeze hook fired ...
my $data = Storable::retrieve($file);
cmp_deeply(
$data,
{
'__CLASS__' => 'Foo',
'undef' => undef,
'float' => 10.5,
'number' => 10,
'string' => 'HELLO WORLD',
'array' => [ 1 .. 10],
'hash' => { map { $_ => undef } 1 .. 10 },
'object' => {
'__CLASS__' => 'Foo',
'number' => 2
},
},
'... got the data struct we expected'
);
}
{
my $foo = Foo->load($file);
( run in 1.654 second using v1.01-cache-2.11-cpan-5a3173703d6 )