Commit | Line | Data |
daa0fd7d |
1 | package 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; |
19 | |
03e5ba80 |
20 | my $point = eval { Point->new( x => 'fifty', y => 'forty' ); }; |
bcbaa845 |
21 | |
03e5ba80 |
22 | if ($@) { |
23 | print "Oops: $@"; |
bcbaa845 |
24 | } |
25 | |
26 | my $point; |
03e5ba80 |
27 | my $xval = 'forty-two'; |
28 | my $xattribute = Point->meta->find_attribute_by_name('x'); |
bcbaa845 |
29 | my $xtype_constraint = $xattribute->type_constraint; |
bcbaa845 |
30 | |
03e5ba80 |
31 | if ( $xtype_constraint->check($xval) ) { |
32 | $point = Point->new( x => $xval, y => 0 ); |
33 | } |
34 | else { |
35 | print "Value: $xval is not an " . $xtype_constraint->name . "\n"; |
36 | } |
bcbaa845 |
37 | |
38 | =head1 DESCRIPTION |
39 | |
03e5ba80 |
40 | This is the Point example from L<Moose::Cookbook::Basics::Recipe1> |
41 | with type checking added. |
42 | |
43 | If we try to assign a string value to an attribute that is an C<Int>, |
44 | Moose will die with an explicit error message. The error will include |
45 | the attribute name, as well as the type constraint name and the value |
46 | which failed the constraint check. |
bcbaa845 |
47 | |
03e5ba80 |
48 | We use C<eval> to catch this error message in C<$@>. |
bcbaa845 |
49 | |
03e5ba80 |
50 | Later, we get the L<Moose::Meta::TypeConstraint> object from a |
51 | L<Moose::Meta::Attribute> and use the L<Moose::Meta::TypeConstraint> |
52 | to check a value directly. |
bcbaa845 |
53 | |
54 | =head1 SEE ALSO |
55 | |
56 | =over 4 |
57 | |
5cfe3805 |
58 | =item L<Moose::Cookbook::Basics::Recipe1> |
bcbaa845 |
59 | |
60 | =item L<Moose::Utils::TypeConstraints> |
61 | |
62 | =item L<Moose::Meta::Attribute> |
63 | |
64 | =back |
65 | |
5cfe3805 |
66 | =cut |