427dfb4795ecb84dea457d82aa9659cb0a218f2a
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Engine / Trait / OnlyWhenBuilt.pm
1 package MooseX::Storage::Engine::Trait::OnlyWhenBuilt;
2 use Moose::Role;
3
4 # we should
5 # only serialize the attribute if it's already built. So, go ahead
6 # and check if the attribute has a predicate. If so, check if it's
7 # set  and then go ahead and look it up.
8 around 'collapse_attribute' => sub {
9     my ($orig, $self, $attr, @args) = @_;
10
11     my $pred = $attr->predicate if $attr->has_predicate;
12     if ($pred) {
13         return () unless $self->object->$pred();
14     }
15
16     return $self->$orig($attr, @args);
17 };
18
19 1;
20
21 __END__
22
23 =pod
24
25 =head1 NAME
26
27 MooseX::Storage::Engine::Trait::OnlyWhenBuilt - An engine trait to bypass serialization
28
29 =head1 SYNOPSIS
30
31     {   package Point;
32         use Moose;
33         use MooseX::Storage;
34
35         with Storage( traits => [qw|OnlyWhenBuilt|] );
36
37         has 'x' => (is => 'rw', lazy_build => 1 );
38         has 'y' => (is => 'rw', lazy_build => 1 );
39         has 'z' => (is => 'rw', builder => '_build_z' );
40
41         sub _build_x { 3 }
42         sub _build_y { expensive_computation() }
43         sub _build_z { 3 }
44     }
45
46     my $p = Point->new( 'x' => 4 );
47
48     # the result of ->pack will contain:
49     # { x => 4, z => 3 }
50     $p->pack;
51
52 =head1 DESCRIPTION
53
54 Sometimes you don't want a particular attribute to be part of the
55 serialization if it has not been built yet. If you invoke C<Storage()>
56 as outlined in the C<Synopsis>, only attributes that have been built
57 (ie, where the predicate returns 'true') will be serialized.
58 This avoids any potentially expensive computations.
59
60 This trait is applied to an instance of L<MooseX::Storage::Engine>, for the
61 user-visible version shown in the SYNOPSIS, see L<MooseX::Storage::Traits::OnlyWhenBuilt>
62
63 =head1 METHODS
64
65 =head2 Introspection
66
67 =over 4
68
69 =item B<meta>
70
71 =back
72
73 =head1 BUGS
74
75 All complex software has bugs lurking in it, and this module is no
76 exception. If you find a bug please either email me, or add the bug
77 to cpan-RT.
78
79 =head1 AUTHOR
80
81 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
82
83 =head1 COPYRIGHT AND LICENSE
84
85 Copyright 2007-2008 by Infinity Interactive, Inc.
86
87 L<http://www.iinteractive.com>
88
89 This library is free software; you can redistribute it and/or modify
90 it under the same terms as Perl itself.
91
92 =cut
93