2a352ad80900eae710c501a073c8fdd6fe29ede8
[gitmo/MooseX-Storage.git] / t / 006_w_custom_type_handlers.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 9;
7 use Test::Deep;
8 use Test::Fatal;
9
10 BEGIN {
11     use_ok('MooseX::Storage');
12     use_ok('MooseX::Storage::Engine');    
13 }
14
15 =pod
16
17 This is just a simple example of defining 
18 a custom type handler to take care of custom
19 inflate and deflate needs. 
20
21 =cut
22
23 {
24     package Bar;
25     use Moose;
26     
27     has 'baz' => (is => 'rw', isa => 'Str');
28     has 'boo' => (is => 'rw', isa => 'Str');    
29     
30     sub encode {
31         my $self = shift;
32         $self->baz . '|' . $self->boo;
33     }
34     
35     sub decode {
36         my ($class, $packed) = @_;
37         my ($baz, $boo) = split /\|/ => $packed;
38         $class->new(
39             baz => $baz,
40             boo => $boo,
41         );
42     }
43     
44     MooseX::Storage::Engine->add_custom_type_handler(
45         'Bar' => (
46             expand   => sub { Bar->decode(shift) },
47             collapse => sub { (shift)->encode    },
48         )
49     );
50     
51     package Foo;
52     use Moose;
53     use MooseX::Storage;
54     
55     with Storage;
56     
57     has 'bar' => (
58         is      => 'ro',
59         isa     => 'Bar',
60         default => sub {
61             Bar->new(baz => 'BAZ', boo => 'BOO')
62         }
63     );
64 }
65
66 my $foo = Foo->new;
67 isa_ok($foo, 'Foo');
68
69 isa_ok($foo->bar, 'Bar');
70
71 cmp_deeply(
72 $foo->pack,
73 {
74     __CLASS__ => "Foo",
75     bar       => "BAZ|BOO",
76 },
77 '... got correct packed structure');
78
79 {
80     my $foo = Foo->unpack({
81         __CLASS__ => "Foo",
82         bar       => "BAZ|BOO",
83     });
84     isa_ok($foo, 'Foo');
85     
86     isa_ok($foo->bar, 'Bar'); 
87     
88     is($foo->bar->baz, 'BAZ', '... got the right stuff');
89     is($foo->bar->boo, 'BOO', '... got the right stuff');
90 }
91
92
93
94
95