Don't use $_ when checking member constraints, since that can conflict with $_ used...
[gitmo/Moose.git] / lib / Moose / Cookbook / Snack / Types.pod
CommitLineData
daa0fd7d 1package Moose::Cookbook::Snack::Types;
bcbaa845 2
daa0fd7d 3# ABSTRACT: Snippets of code for using Types and Type Constraints
4
5__END__
bcbaa845 6
bcbaa845 7
daa0fd7d 8=pod
bcbaa845 9
10=head1 SYNOPSIS
11
12 package Point;
13 use Moose;
03e5ba80 14
15 has 'x' => ( isa => 'Int', is => 'ro' );
16 has 'y' => ( isa => 'Int', is => 'rw' );
17
bcbaa845 18 package main;
2ba649a5 19 use Try::Tiny;
bcbaa845 20
2ba649a5 21 my $point = try {
22 Point->new( x => 'fifty', y => 'forty' );
bcbaa845 23 }
2ba649a5 24 catch {
25 print "Oops: $_";
26 };
bcbaa845 27
28 my $point;
03e5ba80 29 my $xval = 'forty-two';
30 my $xattribute = Point->meta->find_attribute_by_name('x');
bcbaa845 31 my $xtype_constraint = $xattribute->type_constraint;
bcbaa845 32
03e5ba80 33 if ( $xtype_constraint->check($xval) ) {
34 $point = Point->new( x => $xval, y => 0 );
35 }
36 else {
37 print "Value: $xval is not an " . $xtype_constraint->name . "\n";
38 }
bcbaa845 39
40=head1 DESCRIPTION
41
03e5ba80 42This is the Point example from L<Moose::Cookbook::Basics::Recipe1>
43with type checking added.
44
45If we try to assign a string value to an attribute that is an C<Int>,
46Moose will die with an explicit error message. The error will include
47the attribute name, as well as the type constraint name and the value
48which failed the constraint check.
bcbaa845 49
2ba649a5 50We use L<Try::Tiny> to catch this error message.
bcbaa845 51
03e5ba80 52Later, we get the L<Moose::Meta::TypeConstraint> object from a
53L<Moose::Meta::Attribute> and use the L<Moose::Meta::TypeConstraint>
54to check a value directly.
bcbaa845 55
56=head1 SEE ALSO
57
58=over 4
59
5cfe3805 60=item L<Moose::Cookbook::Basics::Recipe1>
bcbaa845 61
62=item L<Moose::Utils::TypeConstraints>
63
64=item L<Moose::Meta::Attribute>
65
66=back
67
5cfe3805 68=cut