1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
|
=pod
=encoding utf-8
=head1 NAME
Type::Tiny::Manual::UsingWithMoo - basic use of Type::Tiny with Moo
=head1 MANUAL
=head2 Type Constraints
Consider the following basic Moo class:
package Horse {
use Moo;
use namespace::autoclean;
has name => ( is => 'ro' );
has gender => ( is => 'ro' );
has age => ( is => 'rw' );
has children => ( is => 'ro', default => sub { [] } );
}
Code like this seems simple enough:
my $br = Horse->new(name => "Bold Ruler", gender => 'm', age => 16);
push @{ $br->children },
Horse->new(name => 'Secretariat', gender => 'm', age => 0);
However, once you step away from very simple use of the class, things can
start to go wrong. When we push a new horse onto C<< @{ $br->children } >>,
we are assuming that C<< $br->children >> returned an arrayref.
What if the code that created the C<< $br >> horse had instantiated it like
this?
my $br = Horse->new(name => "Bold Ruler", children => 'no');
It is for this reason that it's useful for the Horse class to perform
some basic sanity-checking on its own attributes.
package Horse {
use Moo;
use Types::Standard qw( Str Num ArrayRef );
use namespace::autoclean;
has name => ( is => 'ro', isa => Str );
has gender => ( is => 'ro', isa => Str );
has age => ( is => 'rw', isa => Num );
has children => (
is => 'ro',
isa => ArrayRef,
default => sub { return [] },
);
}
Now, if you instantiate a horse like this, it will throw an error:
my $br = Horse->new(name => "Bold Ruler", children => 'no');
The first type constraint we used here was B<Str>. This is type constraint
that requires values to be strings.
Note that although C<undef> is not a string, the empty string is still a
string and you will often want to check that a string is non-empty.
We could have done this:
use Types::Common::String qw( NonEmptyStr );
has name => ( is => 'ro', isa => NonEmptyStr );
While most of the type constraints we will use in this manual are defined
in L<Types::Standard>, the L<Types::Common::String> type library also
defines many useful type constraints.
We have required the horse's age to be a number. This is also a common,
useful type constraint. If we want to make sure it's a whole number, we
could use:
use Types::Standard qw( Int );
has age => ( is => 'rw', isa => Int );
Or because negative numbers make little sense as an age:
use Types::Common::Numeric qw( PositiveOrZeroInt );
has age => ( is => 'rw', isa => PositiveOrZeroInt );
The L<Types::Common::Numeric> library defines many useful subtypes of
B<Int> and B<Num>, such as B<PositiveInt> and B<PositiveOrZeroInt>.
The last type constraint we've used in this example is B<ArrayRef>.
This requires the value to be a reference to an array.
Types::Standard also provides B<HashRef> and B<CodeRef> type constraints.
An example of using the latter:
package Task {
use Moo;
use Types::Standard qw( CodeRef Bool );
has on_success => ( is => 'ro', isa => CodeRef );
has on_failure => ( is => 'ro', isa => CodeRef );
has finished => ( is => 'ro', isa => Bool, default => 0 );
...;
}
my $task = Task->new(
on_success => sub { ... },
on_failure => sub { ... },
...,
);
The B<< Bool >> type constraint accepts "1" as a true value, and
"0", "", or undef as false values. No other values are accepted.
There exists an B<Object> type constraint that accepts any blessed
object.
package Horse {
use Moo;
use Types::Standard qw( Object );
use namespace::autoclean;
...; # name, gender, age, children
has father => ( is => 'ro', isa => Object );
has mother => ( is => 'ro', isa => Object );
}
Finally, another useful type constraint to know about is B<Any>:
use Types::Standard qw( Any );
has stuff => ( is => 'rw', isa => Any );
This type constraint allows any value; it is essentially the same as not doing
any type check, but makes your intent clearer. Where possible, Type::Tiny will
optimize away this type check, so it should have little (if any) impact on
performance.
=head2 Parameterized Types
Let's imagine we want to keep track of our horse's race wins:
package Horse {
use Moo;
use Types::Standard qw( Str Num ArrayRef );
use namespace::autoclean;
...; # name, gender, age, children
has wins => (
is => 'ro',
isa => ArrayRef,
default => sub { return [] },
);
}
We can create a horse like this:
my $br = Horse->new(
name => "Bold Ruler",
gender => 'm',
age => 4,
wins => ["Futurity Stakes 1956", "Juvenile Stakes 1956"],
);
The list of wins is an arrayref of strings. The B<ArrayRef> type constraint
prevents it from being set to a hashref, for example, but it doesn't
ensure that everything in the arrayref is a string. To do that, we need
to parameterize the type constraint:
has wins => (
is => 'ro',
isa => ArrayRef[Str],
default => sub { return [] },
);
Thanks to the B<< ArrayRef[Str] >> parameterized type, the constructor will
throw an error if the arrayref you pass to it contains anything non-string.
An alternative way of writing this is:
has wins => (
is => 'ro',
isa => ArrayRef->of(Str),
default => sub { return [] },
);
Which way you choose is largely a style preference. TIMTOWTDI!
Note that although the constructor and any setter/accessor method will perform
type checks, it is possible to bypass them using:
push @{ $br->wins }, $not_a_string;
The constructor isn't being called here, and although the accessor I<is>
being called, it's being called as a reader, not a writer, so never gets
an opportunity to inspect the value being added. (It is possible to use
C<tie> to solve this, but that will be covered later.)
And of course, if you directly poke at the underlying hashref of the
object, all bets are off:
$br->{wins} = $not_an_arrayref;
So type constraints do have limitations. Careful API design (and not
circumventing the proper API) can help.
The B<HashRef> type constraint can also be parameterized:
package Design {
use Moo;
use Types::Standard qw( HashRef Str );
has colours => ( is => 'ro', isa => HashRef[Str] );
}
my $eiffel65 = Design->new(
colours => { house => "blue", little_window => "blue" },
);
The B<< HashRef[Str] >> type constraint ensures the I<values> of the hashref
are strings; it doesn't check the keys of the hashref because keys in Perl
hashes are always strings!
If you do need to constrain the keys, it is possible to use a parameterized
B<< Map >> constraint:
use Types::Common::String qw( NonEmptyStr );
use Types::Standard qw( Map );
has colours => ( is => 'ro', isa => Map[NonEmptyStr, NonEmptyStr] );
B<Map> takes two parameters; the first is a type to check keys against and
the second is a type to check values against.
Another useful type constraint is the B<< Tuple >> type constraint.
use Types::Standard qw( ArrayRef Tuple );
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
has wins => (
is => 'ro',
isa => ArrayRef[ Tuple[PositiveInt, NonEmptyStr] ],
default => sub { return [] },
);
The B<< Tuple[PositiveInt, NonEmptyStr] >> type constraint checks that a value
is a two-element arrayref where the first element is a positive integer and the
second element is a non-empty string. For example:
my $br = Horse->new(
name => "Bold Ruler",
wins => [
[ 1956, "Futurity Stakes" ],
[ 1956, "Juvenile Stakes" ],
],
);
As you can see, parameterized type constraints may be nested to arbitrary
depth, though of course the more detailed your checks become, the slower
they will perform.
It is possible to have tuples with variable length. For example, we may
wish to include the jockey name in our race wins when it is known.
use Types::Standard qw( ArrayRef Tuple Optional );
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
has wins => (
is => 'ro',
isa => ArrayRef[
Tuple[ PositiveInt, NonEmptyStr, Optional[NonEmptyStr] ]
],
default => sub { return [] },
);
The third element will be checked if it is present, but forgiven if it is
absent.
Or we could just allow tuples to contain an arbitrary list of strings
after the year and race name:
use Types::Standard qw( ArrayRef Tuple Str Slurpy );
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
has wins => (
is => 'ro',
isa => ArrayRef[
Tuple[ PositiveInt, NonEmptyStr, Slurpy[ ArrayRef[Str] ] ]
],
default => sub { return [] },
);
The B<< Slurpy[ ArrayRef[Str] ] >> type will "slurp" all the remaining items
in the tuple into an arrayref and check it against B<< ArrayRef[Str] >>.
It's even possible to do this:
use Types::Standard qw( ArrayRef Tuple Any Slurpy );
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
has wins => (
is => 'ro',
isa => ArrayRef[
Tuple[ PositiveInt, NonEmptyStr, Slurpy[Any] ]
],
default => sub { return [] },
);
With this type constraint, any elements after the first two will be slurped
into an arrayref and we don't check that arrayref at all. (In fact, the
implementation of the B<Tuple> type is smart enough to not bother creating
the temporary arrayref to check.)
B<Dict> is the equivalent of B<Tuple> for checking values of hashrefs.
use Types::Standard qw( ArrayRef Dict Optional );
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
has wins => (
is => 'ro',
isa => ArrayRef[
Dict[
year => PositiveInt,
race => NonEmptyStr,
jockey => Optional[NonEmptyStr],
],
],
default => sub { return [] },
);
An example of using it:
my $br = Horse->new(
name => "Bold Ruler",
wins => [
{ year => 1956, race => "Futurity Stakes", jockey => "Eddie" },
{ year => 1956, race => "Juvenile Stakes" },
],
);
The B<Slurpy> type does work for B<Dict> too:
Dict[
year => PositiveInt,
race => NonEmptyStr,
jockey => Optional[NonEmptyStr],
() => Slurpy[ HashRef[Str] ], # other Str values allowed
]
And C<< Slurpy[Any] >> means what you probably think it means:
Dict[
year => PositiveInt,
race => NonEmptyStr,
jockey => Optional[NonEmptyStr],
() => Slurpy[Any], # allow hashref to contain absolutely anything else
]
Going back to our first example, there's an opportunity to refine our
B<ArrayRef> constraint:
package Horse {
use Moo;
use Types::Standard qw( Str Num ArrayRef );
use namespace::autoclean;
has name => ( is => 'ro', isa => Str );
has gender => ( is => 'ro', isa => Str );
has age => ( is => 'rw', isa => Num );
has children => (
is => 'ro',
isa => ArrayRef[ InstanceOf["Horse"] ],
default => sub { return [] },
);
}
The B<< InstanceOf["Horse"] >> type constraint checks that a value is
a blessed object in the Horse class. So the horse's children should be
an arrayref of other Horse objects.
Internally it just checks C<< $_->isa("Horse") >> on each item in the
arrayref.
It is sometimes useful to instead check C<< $_->DOES($role) >> or
C<< $_->can($method) >> on an object. For example:
package MyAPI::Client {
use Moo;
use Types::Standard qw( HasMethods );
has ua => (is => 'ro', isa => HasMethods["get", "post"] );
}
The B<ConsumerOf> and B<HasMethods> parameterizable types allow you to
easily check roles and methods of objects.
The B<Enum> parameterizable type allows you to accept a more limited set
of string values. For example:
use Types::Standard qw( Enum );
has gender => ( is => 'ro', isa => Enum["m","f"] );
Or if you want a little more flexibility, you can use B<StrMatch> which
allows you to test strings against a regular expression:
use Types::Standard qw( StrMatch );
has gender => ( is => 'ro', isa => StrMatch[qr/^[MF]/i] );
Or B<StrLength> to check the maximum and minimum length of a string:
use Types::Common::String qw( StrLength );
has name => ( is => 'ro', isa => StrLength[3, 100] );
The maximum can be omitted.
Similarly, the maximum and minimum values for a numeric type can be
expressed using B<IntRange> and B<NumRange>:
use Types::Common::Numeric qw( IntRange );
# values over 200 are probably an input error
has age => ( is => 'ro', isa => IntRange[0, 200] );
Parameterized type constraints are one of the most powerful features of
Type::Tiny, allowing a small set of constraints to be combined in
useful ways.
=head2 Type Coercions
It is often good practice to be liberal in what you accept.
package Horse {
use Moo;
use Types::Standard qw( Str Num ArrayRef Bool );
use namespace::autoclean;
...; # name, gender, age, children, wins
has is_alive => ( is => 'rw', isa => Bool, coerce => 1 );
}
The C<coerce> option indicates that if a value is given which I<< does not >>
pass the B<Bool> type constraint, then it should be coerced (converted) into
something that does.
The definition of B<Bool> says that to convert a non-boolean to a bool, you
just do C<< !! $non_bool >>. So all of the following will be living horses:
Horse->new(is_alive => 42)
Horse->new(is_alive => [])
Horse->new(is_alive => "false") # in Perl, string "false" is true!
B<Bool> is the only type constraint in Types::Standard that has a coercion
defined for it. The B<NumericCode>, B<UpperCaseStr>, B<LowerCaseStr>,
B<UpperCaseSimpleStr>, and B<LowerCaseSimpleStr> types from
Types::Common::String also have conversions defined.
The other built-in constraints do not define any coercions because it would
be hard to agree on what it means to coerce from, say, a B<HashRef> to
an B<ArrayRef>. Do we keep the keys? The values? Both?
But it is pretty simple to add your own coercions!
use Types::Standard qw( ArrayRef HashRef Str );
has things => (
is => 'rw',
isa => ArrayRef->plus_coercions(
HashRef, sub { [ values %$_ ] },
Str, sub { [ split /;/, $_ ] },
),
coerce => 1,
);
(Don't ever forget the C<< coerce => 1 >>!)
If a hashref is provided, the values will be used, and if a string is
provided, it will be split on the semicolon. Of course, if an arrayref
if provided, it already passes the type constraint, so no conversion is
necessary.
The coercions should be pairs of "from types" and code to coerce the
value. The code can be a coderef (as above) or just string of Perl code
(as below). Strings of Perl code can usually be optimized better by
Type::Tiny's internals, so are generally preferred. Thanks to Perl's
C<< q{...} >> operator, they can look just as clean and pretty as coderefs.
use Types::Standard qw( ArrayRef HashRef Str );
has things => (
is => 'rw',
isa => ArrayRef->plus_coercions(
HashRef, q{ [ values %$_ ] },
Str, q{ [ split /;/, $_ ] },
),
coerce => 1,
);
Coercions are deeply applied automatically, so the following will do
what you expect.
has inputs => (
is => 'ro',
isa => ArrayRef->of(Bool),
coerce => 1
);
I am, of course, assuming you expect something like:
my $coerced = [ map { !!$_ } @$orig ];
If you were assuming that, congratulations! We are on the same wavelength.
And of course you can still add more coercions to the inherited ones...
has inputs => (
is => 'ro',
isa => ArrayRef->of(Bool)->plus_coercions(Str, sub {...}),
coerce => 1
);
=head2 Type Defaults
A previous example included:
has children => (
is => 'ro',
isa => ArrayRef,
default => sub { return [] },
);
It's actually pretty common that you'll want an arrayref attribute to
default to being an empty arrayref, a numeric attribute to default to
zero, etc. Type::Tiny provides a method for that:
has children => (
is => 'ro',
isa => ArrayRef,
default => ArrayRef->type_default,
);
Many of the types in L<Types::Standard> have sensible type defaults
defined.
=head2 Method Parameters
So far we have just concentrated on the definition of object attributes, but
type constraints are also useful to validate method parameters.
Let's remember our attribute for keeping track of a horse's race wins:
use Types::Standard qw( ArrayRef Tuple Optional );
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
has wins => (
is => 'ro',
isa => ArrayRef[
Tuple[ PositiveInt, NonEmptyStr, Optional[NonEmptyStr] ]
],
default => sub { return [] },
);
Because we don't trust outside code to push new entries onto this array,
let's define a method in our class to do it.
package Horse {
...;
sub add_win {
my $self = shift;
my ($year, $race, $jockey) = @_;
my $win = [
$year,
$race,
$jockey ? $jockey : (),
];
push @{ $self->wins }, $win;
return $self;
}
}
This works pretty well, but we're still not actually checking the values
of C<< $year >>, C<< $race >>, and C<< $jockey >>. Let's use L<Type::Params>
for that:
package Horse {
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
use Type::Params qw( signature );
...;
sub add_win {
state $check = signature(
method => 1, # allow for $self
positional => [
PositiveInt,
NonEmptyStr,
NonEmptyStr, { optional => 1 },
],
);
my ( $self, $year, $race, $jockey ) = $check->(@_);
my $win = [
$year,
$race,
$jockey ? $jockey : (),
];
push @{ $self->wins }, $win;
return $self;
}
}
The first time this method is called, it will compile a coderef called
C<< $check >>. Then every time it is run, C<< $check >> will be called
to check the method's parameters. It will throw an exception if they
fail. C<< $check >> will also perform coercions if types have them
(and you don't even need to remember C<< coerce => 1 >>; it's automatic)
and can even add in defaults:
state $check = signature(
method => 1,
positional => [
PositiveInt,
NonEmptyStr,
NonEmptyStr, { default => sub { "Eddie" } },
],
);
On older versions of Perl (prior to 5.10), C<state> variables are not
available. A workaround is to replace this:
sub foo {
state $x = bar();
...;
}
With this:
{ # outer braces prevent other subs seeing $x
my $x; # declare $x before sub foo()
sub foo {
$x = bar();
...;
}
}
(While we're having a general Perl syntax lesson, I'll note that
C<< &$check >> with an ampersand and no parentheses is a shortcut for
C<< $check->(@_) >> and actually runs slightly faster because it reuses
the C<< @_ >> array for the called coderef. A lot of people dislike calling
subs with an ampersand, so we will stick to the C<< $check->(@_) >> syntax
in these examples. But do consider using the shortcut!)
The generalized syntax for positional parameters in C<signature> is:
state $check = signature(
%general_options,
positional => [
TypeForFirstParam, \%options_for_first_param,
TypeForSecondParam, \%options_for_second_param,
...,
],
);
As a shortcut for the C<< { optional => 1 } >> option, you can just use
B<Optional> like in B<Tuple>.
state $check = signature(
method => 1,
positional => [
PositiveInt,
NonEmptyStr,
Optional[NonEmptyStr],
],
);
You can also use C<0> and C<1> as shortcuts for B<< Optional[Any] >> and
B<< Any >>. The following checks that the first parameter is a positive
integer, the second parameter is required (but doesn't care what value
it is) and the third parameter is allowed but not required.
state $check = signature positional => [ PositiveInt, 1, 0 ];
It is possible to accept a variable number of values using B<Slurpy>:
package Horse {
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
use Types::Standard qw( ArrayRef Slurpy );
use Type::Params qw( signature );
...;
sub add_wins_for_year {
state $check = signature(
method => 1,
positional => [
PositiveInt,
Slurpy[ ArrayRef[NonEmptyStr] ],
],
);
my ( $self, $year, $races ) = $check->(@_);
for my $race (@$races) {
push @{ $self->wins }, [$year, $race];
}
return $self;
}
}
It would be called like this:
$bold_ruler->add_wins_for_year(
1956,
"Futurity Stakes",
"Juvenile Stakes",
);
The additional parameters are slurped into an arrayref and checked against
B<< ArrayRef[NonEmptyStr] >>.
Optional parameters are only allowed after required parameters, and B<Slurpy>
parameters are only allowed at the end. (And there can only be a at most
one B<Slurpy> parameter!)
For methods that accept more than one or two parameters, it is often a good
idea to provide them as a hash. For example:
$horse->add_win(
year => 1956,
race => "Futurity Stakes",
jockey => "Eddie",
);
This can make your code more readable.
To accept named parameters, use the C<named> option instead of C<positional>.
package Horse {
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
use Type::Params qw( signature );
...;
sub add_win {
state $check = signature(
method => 1,
named => [
year => PositiveInt,
race => NonEmptyStr,
jockey => NonEmptyStr, { optional => 1 },
],
);
my ( $self, $arg ) = $check->(@_);
my $win = [
$arg->year,
$arg->race,
$arg->has_jockey ? $arg->jockey : (),
];
push @{ $self->wins }, $win;
return $self;
}
}
The C<named> option will bundle all of your named arguments into an object
C<< $arg >>. It allows your method to be called with a list of name-value
pairs or a hashref:
$horse->add_win(
year => 1956,
race => "Futurity Stakes",
jockey => "Eddie",
);
$horse->add_win( {
year => 1956,
race => "Juvenile Stakes",
} );
It is also possible for your check to I<accept> named parameters but
I<return> a positional list of parameters, using C<named_to_list>.
package Horse {
use Types::Common::Numeric qw( PositiveInt );
use Types::Common::String qw( NonEmptyStr );
use Type::Params qw( signature );
...;
sub add_win {
state $check = signature(
method => 1,
named => [
year => PositiveInt,
race => NonEmptyStr,
jockey => NonEmptyStr, { optional => 1 },
],
named_to_list => 1,
);
my ( $self, $year, $race, $jockey ) = $check->(@_);
my $win = [
$year,
$race,
$jockey ? $jockey : (),
];
push @{ $self->wins }, $win;
return $self;
}
}
Optional and Slurpy named parameters are supported as you'd expect.
For more information on Type::Params, and third-party alternatives,
see L<Type::Tiny::Manual::Params>.
=head1 NEXT STEPS
Congratulations! I know this was probably a lot to take in, but you've
covered all of the essentials.
You can now set type constraints and coercions for attributes and method
parameters in Moo! You are familiar with a lot of the most important
and useful type constraints and understand parameterization and how
it can be used to build more specific type constraints.
(And I'll let you in on a secret. Using Type::Tiny with L<Moose> or
L<Mouse> instead of L<Moo> is exactly the same. You can just replace
C<< use Moo >> with C<< use Moose >> in any of these examples and they should
work fine!)
Here's your next step:
=over
=item * L<Type::Tiny::Manual::UsingWithMoo2>
Advanced use of Type::Tiny with Moo, including unions and intersections,
C<stringifies_to>, C<numifies_to>, C<with_attribute_values>, and C<where>.
=back
=head1 NOTES
On very old versions of Moo C<< coerce => 1 >> is not supported. Instead
you will need to provide a coderef or object overloading C<< &{} >> to
coerce. Type::Tiny can provide you with an overloaded object.
package Horse {
use Moo;
use Types::Standard qw( Str Num ArrayRef Bool );
use namespace::autoclean;
...; # name, gender, age, children, wins
has is_alive => (
is => 'rw',
isa => Bool,
coerce => Bool->coercion, # overloaded object
);
}
If you have a very old version of Moo, please upgrade to at least Moo 1.006000
which was the version that added support for C<< coerce => 1 >>.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2013-2014, 2017-2023 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.
=head1 DISCLAIMER OF WARRANTIES
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.
=cut
|