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; |
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 | |
c4fde3b5 |
42 | This is the Point example from |
43 | L<Moose::Cookbook::Basics::Point_AttributesAndSubclassing> with type checking |
44 | added. |
03e5ba80 |
45 | |
46 | If we try to assign a string value to an attribute that is an C<Int>, |
47 | Moose will die with an explicit error message. The error will include |
48 | the attribute name, as well as the type constraint name and the value |
49 | which failed the constraint check. |
bcbaa845 |
50 | |
2ba649a5 |
51 | We use L<Try::Tiny> to catch this error message. |
bcbaa845 |
52 | |
03e5ba80 |
53 | Later, we get the L<Moose::Meta::TypeConstraint> object from a |
54 | L<Moose::Meta::Attribute> and use the L<Moose::Meta::TypeConstraint> |
55 | to check a value directly. |
bcbaa845 |
56 | |
57 | =head1 SEE ALSO |
58 | |
59 | =over 4 |
60 | |
c4fde3b5 |
61 | =item L<Moose::Cookbook::Basics::Point_AttributesAndSubclassing> |
bcbaa845 |
62 | |
63 | =item L<Moose::Utils::TypeConstraints> |
64 | |
65 | =item L<Moose::Meta::Attribute> |
66 | |
67 | =back |
68 | |
5cfe3805 |
69 | =cut |