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