Type::Tiny::Manual::UsingWithMoo - how to use Type::Tiny and Type::Library with Moo
{ package Person; use Moo; use Types::Standard qw( Str Int ); use Type::Utils qw( declare as where inline_as coerce from ); has name => ( is => "ro", isa => Str, ); my $PositiveInt = declare as Int, where { $_ > 0 }, inline_as { "$_ =~ /^[0-9]\$/ and $_ > 0" }; coerce $PositiveInt, from Int, q{ abs $_ }; has age => ( is => "rwp", isa => $PositiveInt, coerce => $PositiveInt->coercion, ); sub get_older { my $self = shift; my ($years) = @_; $PositiveInt->assert_valid($years); $self->_set_age($self->age + $years); } }
Type::Tiny is tested with Moo 1.001000.
Type::Tiny overloads &{}. Moo supports using objects that overload &{} as isa constraints, so Type::Tiny objects can directly be used in isa.
&{}
isa
Moo doesn't support coerce => 1 but requires a coderef as a coercion. However, again it supports using objects that overload &{}, which Type::Coercion does, allowing coerce => $Type->coercion to work.
coerce => 1
coerce => $Type->coercion
Type::Tiny hooks into Moo's HandleMoose interface to ensure that type constraints get inflated to Moose type constraints if and when Moo inflates your class to a full Moose class.
The usual advice for optimizing type constraints applies: use type constraints which can be inlined whenever possible, and define coercions as strings rather than coderefs.
There is a patch in the Moo repository that will enable inlining to work http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=gitmo/Moo.git;a=shortlog;h=refs/heads/coderef-overload.
For examples using Type::Tiny with Moo see the SYNOPSIS sections of Type::Tiny and Type::Library, and the files moo.t and moo-coercion.t and moo-inflation.t in the Type-Tiny test suite.
moo.t
moo-coercion.t
moo-inflation.t
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 Type::Tiny, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Type::Tiny
CPAN shell
perl -MCPAN -e shell install Type::Tiny
For more information on module installation, please visit the detailed CPAN module installation guide.