1 package MooseX::Storage::Engine::Trait::OnlyWhenBuilt;
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) = @_;
11 my $pred = $attr->predicate if $attr->has_predicate;
13 return () unless $self->object->$pred();
16 return $self->$orig($attr, @args);
27 MooseX::Storage::Engine::Trait::OnlyWhenBuilt - An engine trait to bypass serialization
35 with Storage( traits => [qw|OnlyWhenBuilt|] );
37 has 'x' => (is => 'rw', lazy_build => 1 );
38 has 'y' => (is => 'rw', lazy_build => 1 );
39 has 'z' => (is => 'rw', builder => '_build_z' );
42 sub _build_y { expensive_computation() }
46 my $p = Point->new( 'x' => 4 );
48 # the result of ->pack will contain:
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.
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>
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
81 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
83 =head1 COPYRIGHT AND LICENSE
85 Copyright 2007-2008 by Infinity Interactive, Inc.
87 L<http://www.iinteractive.com>
89 This library is free software; you can redistribute it and/or modify
90 it under the same terms as Perl itself.