Moose::Util::TypeConstraints - Type constraint system for Moose |
Moose::Util::TypeConstraints - Type constraint system for Moose
use Moose::Util::TypeConstraints;
type 'Num' => where { Scalar::Util::looks_like_number($_) };
subtype 'Natural' => as 'Num' => where { $_ > 0 };
subtype 'NaturalLessThanTen' => as 'Natural' => where { $_ < 10 } => message { "This number ($_) is not less than ten!" };
coerce 'Num' => from 'Str' => via { 0+$_ };
enum 'RGBColors' => qw(red green blue);
This module provides Moose with the ability to create custom type contraints to be used in attribute definition.
This is NOT a type system for Perl 5. These are type constraints, and they are not used by Moose unless you tell it to. No type inference is performed, expression are not typed, etc. etc. etc.
This is simply a means of creating small constraint functions which can be used to simplify your own type-checking code, with the added side benefit of making your intentions clearer through self-documentation.
It is always a good idea to quote your type and subtype names.
This is to prevent perl from trying to execute the call as an indirect object call. This issue only seems to come up when you have a subtype the same name as a valid class, but when the issue does arise it tends to be quite annoying to debug.
So for instance, this:
subtype DateTime => as Object => where { $_->isa('DateTime') };
will Just Work, while this:
use DateTime; subtype DateTime => as Object => where { $_->isa('DateTime') };
will fail silently and cause many headaches. The simple way to solve this, as well as future proof your subtypes from classes which have yet to have been created yet, is to simply do this:
use DateTime; subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
This module also provides a simple hierarchy for Perl 5 types, here is that hierarchy represented visually.
Any Item Bool Maybe[`a] Undef Defined Value Num Int Str ClassName Ref ScalarRef ArrayRef[`a] HashRef[`a] CodeRef RegexpRef GlobRef FileHandle Object Role
NOTE: Any type followed by a type parameter [`a]
can be
parameterized, this means you can say:
ArrayRef[Int] # an array of intergers HashRef[CodeRef] # a hash of str to CODE ref mappings Maybe[Str] # value may be a string, may be undefined
NOTE: The Undef
type constraint for the most part works
correctly now, but edge cases may still exist, please use it
sparringly.
NOTE: The ClassName
type constraint does a complex package
existence check. This means that your class must be loaded for
this type constraint to pass. I know this is not ideal for all,
but it is a saner restriction than most others.
Since the types created by this module are global, it is suggested that you namespace your types just as you would namespace your modules. So instead of creating a Color type for your My::Graphics module, you would call the type My::Graphics::Color instead.
This module should play fairly nicely with other constraint
modules with only some slight tweaking. The where
clause
in types is expected to be a CODE
reference which checks
it's first argument and returns a boolean. Since most constraint
modules work in a similar way, it should be simple to adapt
them to work with Moose.
For instance, this is how you could use it with the Declare::Constraints::Simple manpage to declare a completely new type.
type 'HashOfArrayOfObjects' => IsHashRef( -keys => HasLength, -values => IsArrayRef( IsObject ));
For more examples see the t/200_examples/204_example_w_DCS.t test file.
Here is an example of using the Test::Deep manpage and it's non-test
related eq_deeply
function.
type 'ArrayOfHashOfBarsAndRandomNumbers' => where { eq_deeply($_, array_each(subhashof({ bar => isa('Bar'), random_number => ignore() }))) };
For a complete example see the t/200_examples/205_example_w_TestDeep.t test file.
The following functions are used to create type constraints. They will then register the type constraints in a global store where Moose can get to them if it needs to.
See the SYNOPSIS for an example of how to use these.
$class
and the metaclass
the Moose::Meta::TypeConstraint::Class manpage.
$role
and the metaclass
the Moose::Meta::TypeConstraint::Role manpage.
Str
and
will match any of the items in @values
. It is case sensitive.
See the SYNOPSIS for a simple example.
NOTE: This is not a true proper enum type, it is simple a convient constraint builder.
$name
, @values
pair,
this will create an unnamed enum. This can then be used in an attribute
definition like so:
has 'sort_order' => ( is => 'ro', isa => enum([qw[ ascending descending ]]), );
NOTE: You should only use this if you know what you are doing, all the built in types use this, so your subtypes (assuming they are shallow) will not likely need to use this.
Type constraints can also contain type coercions as well. If you ask your accessor to coerce, then Moose will run the type-coercion code first, followed by the type constraint check. This feature should be used carefully as it is very powerful and could easily take off a limb if you are not careful.
See the SYNOPSIS for an example of how to use these.
$pipe_seperated_types
or a list of @type_constraint_names
,
this will return a the Moose::Meta::TypeConstraint::Union manpage instance.
$type_name
in the form of:
BaseType[ContainerType]
this will extract the base type and container type and build an instance of the Moose::Meta::TypeConstraint::Parameterized manpage for it.
$type_name
.
If it cannot find it in the registry, it will see if it should be a union or
container type an create one if appropriate
find_or_parse_type_constraint
with the type name.
If no type is found or created, but $options_for_anon_type
are provided, it
will create the corresponding type.
This was used by the does
and isa
parameters to the Moose::Meta::Attribute manpage
and are now superseded by find_or_create_isa_type_constraint
and
find_or_create_does_type_constraint
.
The isa
variant will use create_class_type_constraint
and the does
variant will use create_role_type_constraint
.
find_type_constraint ($type_name)
if you
want to.
$type
to the list of parameterizable types
All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or add the bug to cpan-RT.
Stevan Little <stevan@iinteractive.com>
Copyright 2006-2008 by Infinity Interactive, Inc.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Moose::Util::TypeConstraints - Type constraint system for Moose |