MooseX::CustomInitArgs - define multiple init args with custom processing
package Circle { use Moose; use MooseX::CustomInitArgs; has radius => ( is => 'ro', isa => 'Num', required => 1, init_args => [ 'r', 'diameter' => sub { $_ / 2 }, ], ); } # All three are equivalent... my $circle = Circle->new(radius => 1); my $circle = Circle->new(r => 1); my $circle = Circle->new(diameter => 2);
MooseX::CustomInitArgs allows Moose attributes to be initialized from alternative initialization arguments. If you find yourself wishing that Moose's built-in init_arg option took an arrayref, then this is what you want.
MooseX::CustomInitArgs
init_arg
MooseX::MultiInitArg also does this, but MooseX::CustomInitArgs has an additional feature: it can optionally pre-process each initialization argument. This happens prior to type coercian and constraint checks.
(Also at the time of writing, MooseX::MultiInitArg suffers from a bug where it breaks when a class is immutablized.)
MooseX::MultiInitArg
The constructor cannot be called with multiple initialization arguments for the same attribute. Given the class in the example, this would throw an error:
my $circle = Circle->new(radius => 1, diameter => 100);
The following would also throw an error, even though it's slightly more sensible:
my $circle = Circle->new(radius => 1, diameter => 2);
The init_args attribute option is conceptually a hash mapping initialization argument names to methods which pre-process them. The methods can be given as coderefs, or the names of class methods as strings (or scalar refs).
init_args
You can provide this hash mapping as an actual hashref, or (as in the "SYNOPSIS") as an arrayref suitable for input to Data::OptList. In either case it will be coerced to MooseX::CustomInitArgs's internal representation which is a Data::OptList-style arrayref of arrayrefs.
Data::OptList
init_args cannot be used on attributes with init_arg => undef. MooseX::CustomInitArgs will throw an error if you do.
init_arg => undef
Please report any bugs to http://rt.cpan.org/Dist/Display.html?Queue=MooseX-CustomInitArgs.
MooseX::MultiInitArg, MooseX::FunkyAttributes.
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2013 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
To install MooseX::CustomInitArgs, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MooseX::CustomInitArgs
CPAN shell
perl -MCPAN -e shell install MooseX::CustomInitArgs
For more information on module installation, please visit the detailed CPAN module installation guide.