Commit | Line | Data |
bcbaa845 |
1 | |
2 | =pod |
3 | |
4 | =head1 NAME |
5 | |
6 | Moose::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 |
38 | This is the Point example from L<Moose::Cookbook::Basics::Recipe1> |
39 | with type checking added. |
40 | |
41 | If we try to assign a string value to an attribute that is an C<Int>, |
42 | Moose will die with an explicit error message. The error will include |
43 | the attribute name, as well as the type constraint name and the value |
44 | which failed the constraint check. |
bcbaa845 |
45 | |
03e5ba80 |
46 | We use C<eval> to catch this error message in C<$@>. |
bcbaa845 |
47 | |
03e5ba80 |
48 | Later, we get the L<Moose::Meta::TypeConstraint> object from a |
49 | L<Moose::Meta::Attribute> and use the L<Moose::Meta::TypeConstraint> |
50 | to 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 | |
66 | Jess Robinson <cpan@desert-island.me.uk> |
67 | |
68 | =head1 COPYRIGHT AND LICENSE |
69 | |
7e0492d3 |
70 | Copyright 2006-2010 by Infinity Interactive, Inc. |
bcbaa845 |
71 | |
72 | L<http://www.iinteractive.com> |
73 | |
74 | This library is free software; you can redistribute it and/or modify |
75 | it under the same terms as Perl itself. |
76 | |
5cfe3805 |
77 | =cut |