1 package MooseX::UndefTolerant;
6 use MooseX::UndefTolerant::Attribute;
7 use MooseX::UndefTolerant::Constructor;
11 Moose::Exporter->setup_import_methods(
13 attribute => [ 'MooseX::UndefTolerant::Attribute' ],
14 constructor => [ 'MooseX::UndefTolerant::Constructor' ],
24 MooseX::UndefTolerant - Make your attribute(s) tolerant to undef initialization
31 use MooseX::UndefTolerant;
36 predicate => 'has_name'
39 # Meanwhile, under the city...
42 my $class = My::Class->new(name => undef);
43 $class->has_name # False!
45 Or, if you only want one attribute to have this behaviour:
50 use MooseX::UndefTolerant::Attribute;
53 traits => [ qw(MooseX::UndefTolerant::Attribute)],
56 predicate => 'has_bar'
61 Loading this module in your L<Moose> class makes initialization of your
62 attributes tolerant of undef. If you specify the value of undef to any of
63 the attributes they will not be initialized. Effectively behaving as if you
64 had not provided a value at all.
68 I often found myself in this quandry:
80 my $foo = ... # get the param from something
82 my $class = My:Class->new(foo => $foo, bar => 123);
84 What if foo is undefined? I didn't want to change my attribute to be
85 Maybe[Str] and I still want my predicate (C<has_foo>) to work. The only
89 $class = My:CLass->new(foo => $foo, bar => 123);
91 $class = My:CLass->new(bar => 123);
94 Or some type of codemulch using ternarys. This module allows you to make
95 your attributes more tolerant of undef so that you can keep the first
96 example: have your cake and eat it too!
98 =head1 USE IN YOUR MOOSE EXPORTER
100 If you already have a custom Moose exporter class and you want this
101 behaviour everywhere, you can add these roles there with this call, in
102 your C<init_meta> routine:
104 Moose::Util::MetaRole::apply_metaroles(
106 attribute => [ 'MooseX::UndefTolerant::Attribute' ],
107 constructor => [ 'MooseX::UndefTolerant::Constructor' ],
109 for => $args{for_class},
116 Cory G Watson, C<< <gphat at cpan.org> >>
118 =head1 ACKNOWLEDGEMENTS
120 Many thanks to the crew in #moose who talked me through this module:
122 Hans Dieter Pearcey (confound)
128 Dylan Hardison (dylan)
130 Jay Shirley (jshirley)
134 =head1 COPYRIGHT & LICENSE
136 Copyright 2009 Cory G Watson.
138 This program is free software; you can redistribute it and/or modify it
139 under the terms of either: the GNU General Public License as published
140 by the Free Software Foundation; or the Artistic License.
142 See http://dev.perl.org/licenses/ for more information.