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