1MooseX::SingleArg(3pm)User Contributed Perl DocumentationMooseX::SingleArg(3pm)
2
3
4
6 MooseX::SingleArg - No-fuss instantiation of Moose objects using a
7 single argument.
8
10 package Person;
11 use Moose;
12
13 use MooseX::SingleArg;
14
15 single_arg 'name';
16
17 has name => ( is=>'ro', isa=>'Str' );
18
19 my $john = Person->new( 'John Doe' );
20 print $john->name();
21
23 This module allows Moose instances to be constructed with a single
24 argument. Your class or role must use this module and then use the
25 single_arg sugar to declare which attribute will be assigned the single
26 argument value.
27
28 If the class is constructed using the typical argument list name/value
29 pairs, or with a hashref, then things work as is usual. But, if the
30 arguments are a single non-hashref value then that argument will be
31 assigned to whatever attribute you have declared.
32
33 The reason for this module's existence is that when people want this
34 feature they usually find
35 Moose::Cookbook::Basics::Person_BUILDARGSAndBUILD which asks that
36 something like the following be written:
37
38 around BUILDARGS => sub {
39 my $orig = shift;
40 my $class = shift;
41
42 if ( @_ == 1 && ! ref $_[0] ) {
43 return $class->$orig(ssn => $_[0]);
44 }
45 else {
46 return $class->$orig(@_);
47 }
48 };
49
50 The above is complex boilerplate for a simple feature. This module
51 aims to make it simple and fool-proof to support single-argument Moose
52 object construction.
53
55 If setting a custom init_arg for an attribute which you will be
56 assigning as the single_arg then use the init_arg value, rather than
57 the attribute key, for it. For example:
58
59 single_arg 'moniker';
60 has name => ( is=>'ro', isa=>'Str', init_arg=>'moniker' );
61
63 An optional force parameter may be specified:
64
65 single_arg name => (
66 force => 1,
67 );
68
69 This causes constructor argument processing to only work in single-
70 argument mode. If more than one argument is passed then an error will
71 be thrown. The benefit of forcing single argument processing is that
72 hashrefs may now be used as the value of the single argument when force
73 is on.
74
76 MooseX::OneArgNew solves the same problem that this module solves. I
77 considered using OneArgNew for my own needs, but found it oddly
78 cumbersome and confusing. Maybe that's just me, but I hope that this
79 module's design is much simpler to comprehend and more natural to use.
80
82 Aran Clary Deltac <bluefeet@gmail.com>
83
85 · Xavier Guimard <x.guimard@free.fr>
86
87 · Mohammad S Anwar <mohammad.anwar@yahoo.com>
88
90 This is free software; you can redistribute it and/or modify it under
91 the same terms as the Perl 5 programming language system itself.
92
93
94
95perl v5.28.1 2019-02-18 MooseX::SingleArg(3pm)