Version 0.32
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Traits / OnlyWhenBuilt.pm
CommitLineData
76218b46 1package MooseX::Storage::Traits::OnlyWhenBuilt;
2use Moose::Role;
3
e44b5f54 4our $VERSION = '0.32';
76218b46 5our $AUTHORITY = 'cpan:STEVAN';
6
59abaf70 7requires 'pack';
8requires 'unpack';
9
10around 'pack' => sub {
11 my ($orig, $self, %args) = @_;
12 $args{engine_traits} ||= [];
13 push(@{$args{engine_traits}}, 'OnlyWhenBuilt');
14 $self->$orig(%args);
15};
16
17around 'unpack' => sub {
18 my ($orig, $self, $data, %args) = @_;
19 $args{engine_traits} ||= [];
20 push(@{$args{engine_traits}}, 'OnlyWhenBuilt');
21 $self->$orig($data, %args);
22};
23
f82612bc 24no Moose::Role;
25
76218b46 261;
27
28__END__
29
30=pod
31
32=head1 NAME
33
34MooseX::Storage::Traits::OnlyWhenBuilt - A custom trait to bypass serialization
35
36=head1 SYNOPSIS
37
38
39 { package Point;
40 use Moose;
41 use MooseX::Storage;
ec725183 42
76218b46 43 with Storage( traits => [qw|OnlyWhenBuilt|] );
ec725183 44
76218b46 45 has 'x' => (is => 'rw', lazy_build => 1 );
46 has 'y' => (is => 'rw', lazy_build => 1 );
47 has 'z' => (is => 'rw', builder => '_build_z' );
ec725183 48
76218b46 49 sub _build_x { 3 }
50 sub _build_y { expensive_computation() }
51 sub _build_z { 3 }
ec725183 52
76218b46 53 }
ec725183 54
76218b46 55 my $p = Point->new( 'x' => 4 );
ec725183 56
76218b46 57 # the result of ->pack will contain:
58 # { x => 4, z => 3 }
59 $p->pack;
ec725183 60
76218b46 61=head1 DESCRIPTION
62
ec725183 63Sometimes you don't want a particular attribute to be part of the
76218b46 64serialization if it has not been built yet. If you invoke C<Storage()>
65as outlined in the C<Synopsis>, only attributes that have been built
66(ie, where the predicate returns 'true') will be serialized.
67This avoids any potentially expensive computations.
68
69See the SYNOPSIS for a nice example that can be easily cargo-culted.
70
71=head1 METHODS
72
73=head2 Introspection
74
75=over 4
76
77=item B<meta>
78
79=back
80
81=head1 BUGS
82
ec725183 83All complex software has bugs lurking in it, and this module is no
76218b46 84exception. If you find a bug please either email me, or add the bug
85to cpan-RT.
86
87=head1 AUTHOR
88
89Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
90
91=head1 COPYRIGHT AND LICENSE
92
93Copyright 2007-2008 by Infinity Interactive, Inc.
94
95L<http://www.iinteractive.com>
96
97This library is free software; you can redistribute it and/or modify
98it under the same terms as Perl itself.
99
100=cut