1 package MooseX::AlwaysCoerce;
2 # ABSTRACT: Automatically enable coercions for Moose attributes
7 use namespace::autoclean 0.12;
9 use MooseX::ClassAttribute 0.24 ();
11 use Moose::Util::MetaRole;
14 Moose::Exporter->setup_import_methods;
23 use MooseX::AlwaysCoerce;
24 use MyTypeLib 'SomeType';
26 has foo => (is => 'rw', isa => SomeType); # coerce => 1 automatically added
28 # same, MooseX::ClassAttribute is automatically applied
29 class_has bar => (is => 'rw', isa => SomeType);
33 Have you ever spent an hour or more trying to figure out "WTF, why did my
34 coercion not run?" only to find out that you forgot C<< coerce => 1 >> ?
36 Just load this module in your L<Moose> class and C<< coerce => 1 >> will be
37 enabled for every attribute and class attribute automatically.
39 Use C<< coerce => 0 >> to disable a coercion explicitly.
44 package MooseX::AlwaysCoerce::Role::Meta::Attribute;
45 use namespace::autoclean;
48 around should_coerce => sub {
52 my $current_val = $self->$orig(@_);
54 return $current_val if defined $current_val;
56 return 1 if $self->type_constraint && $self->type_constraint->has_coercion;
60 package MooseX::AlwaysCoerce::Role::Meta::Class;
61 use namespace::autoclean;
63 use Moose::Util::TypeConstraints;
65 around add_class_attribute => sub {
68 my ($what, %opts) = @_;
70 if (exists $opts{isa}) {
71 my $type = Moose::Util::TypeConstraints::find_or_parse_type_constraint($opts{isa});
72 $opts{coerce} = 1 if not exists $opts{coerce} and $type->has_coercion;
75 $self->$next($what, %opts);
79 my (undef, undef, $init_meta) = Moose::Exporter->build_import_methods(
81 install => [ qw(import unimport) ],
84 attribute => ['MooseX::AlwaysCoerce::Role::Meta::Attribute'],
85 class => ['MooseX::AlwaysCoerce::Role::Meta::Class'],
89 (Moose->VERSION >= 1.9900
90 ? (applied_attribute => ['MooseX::AlwaysCoerce::Role::Meta::Attribute'])
92 role => ['MooseX::AlwaysCoerce::Role::Meta::Class'],
97 my ($class, %options) = @_;
98 my $for_class = $options{for_class};
100 MooseX::ClassAttribute->import({ into => $for_class });
102 # call generated method to do the rest of the work.
107 # vim:et sts=4 sw=4 tw=0:
115 Please report any bugs or feature requests to C<bug-moosex-alwayscoerce at rt.cpan.org>, or through
116 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MooseX-AlwaysCoerce>. I will be notified, and then you'll
117 automatically be notified of progress on your bug as I make changes.
121 You can find more information at:
125 =item * RT: CPAN's request tracker
127 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-AlwaysCoerce>
129 =item * AnnoCPAN: Annotated CPAN documentation
131 L<http://annocpan.org/dist/MooseX-AlwaysCoerce>
135 L<http://cpanratings.perl.org/d/MooseX-AlwaysCoerce>
139 L<http://search.cpan.org/dist/MooseX-AlwaysCoerce/>
143 =head1 ACKNOWLEDGEMENTS
145 My own stupidity, for inspiring me to write this module.
147 Dave Rolsky, for telling me how to do it the L<Moose> way.