Fix typo in Extending::Recipe1
[gitmo/Moose.git] / lib / Moose / Cookbook / Snack / Types.pod
CommitLineData
bcbaa845 1
2=pod
3
4=head1 NAME
5
6Moose::Cookbook::Snack::Types - Snippets of code for using Types and Type Constraints
7
8=head1 SYNOPSIS
9
10 package Point;
11 use Moose;
03e5ba80 12
13 has 'x' => ( isa => 'Int', is => 'ro' );
14 has 'y' => ( isa => 'Int', is => 'rw' );
15
bcbaa845 16 package main;
17
03e5ba80 18 my $point = eval { Point->new( x => 'fifty', y => 'forty' ); };
bcbaa845 19
03e5ba80 20 if ($@) {
21 print "Oops: $@";
bcbaa845 22 }
23
24 my $point;
03e5ba80 25 my $xval = 'forty-two';
26 my $xattribute = Point->meta->find_attribute_by_name('x');
bcbaa845 27 my $xtype_constraint = $xattribute->type_constraint;
bcbaa845 28
03e5ba80 29 if ( $xtype_constraint->check($xval) ) {
30 $point = Point->new( x => $xval, y => 0 );
31 }
32 else {
33 print "Value: $xval is not an " . $xtype_constraint->name . "\n";
34 }
bcbaa845 35
36=head1 DESCRIPTION
37
03e5ba80 38This is the Point example from L<Moose::Cookbook::Basics::Recipe1>
39with type checking added.
40
41If we try to assign a string value to an attribute that is an C<Int>,
42Moose will die with an explicit error message. The error will include
43the attribute name, as well as the type constraint name and the value
44which failed the constraint check.
bcbaa845 45
03e5ba80 46We use C<eval> to catch this error message in C<$@>.
bcbaa845 47
03e5ba80 48Later, we get the L<Moose::Meta::TypeConstraint> object from a
49L<Moose::Meta::Attribute> and use the L<Moose::Meta::TypeConstraint>
50to check a value directly.
bcbaa845 51
52=head1 SEE ALSO
53
54=over 4
55
5cfe3805 56=item L<Moose::Cookbook::Basics::Recipe1>
bcbaa845 57
58=item L<Moose::Utils::TypeConstraints>
59
60=item L<Moose::Meta::Attribute>
61
62=back
63
64=head1 AUTHOR
65
66Jess Robinson <cpan@desert-island.me.uk>
67
68=head1 COPYRIGHT AND LICENSE
69
2840a3b2 70Copyright 2006-2009 by Infinity Interactive, Inc.
bcbaa845 71
72L<http://www.iinteractive.com>
73
74This library is free software; you can redistribute it and/or modify
75it under the same terms as Perl itself.
76
5cfe3805 77=cut