Add docs for the undocumented classes
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Engine / Trait / OnlyWhenBuilt.pm
CommitLineData
a473d69d 1package MooseX::Storage::Engine::Trait::OnlyWhenBuilt;
2use Moose::Role;
3
4eafd265 4# we should
5# only serialize the attribute if it's already built. So, go ahead
511f9c4b 6# and check if the attribute has a predicate. If so, check if it's
4eafd265 7# set and then go ahead and look it up.
8around '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};
a473d69d 18
191;
20
511f9c4b 21__END__
22
23=pod
24
25=head1 NAME
26
27MooseX::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
54Sometimes you don't want a particular attribute to be part of the
55serialization if it has not been built yet. If you invoke C<Storage()>
56as outlined in the C<Synopsis>, only attributes that have been built
57(ie, where the predicate returns 'true') will be serialized.
58This avoids any potentially expensive computations.
59
60This trait is applied to an instance of L<MooseX::Storage::Engine>, for the
61user-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
75All complex software has bugs lurking in it, and this module is no
76exception. If you find a bug please either email me, or add the bug
77to cpan-RT.
78
79=head1 AUTHOR
80
81Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
82
83=head1 COPYRIGHT AND LICENSE
84
85Copyright 2007-2008 by Infinity Interactive, Inc.
86
87L<http://www.iinteractive.com>
88
89This library is free software; you can redistribute it and/or modify
90it under the same terms as Perl itself.
91
92=cut
93