From: Shawn M Moore Date: Thu, 5 Feb 2009 02:23:53 +0000 (+0000) Subject: Implement basic usage of "enum" type constraints X-Git-Tag: 0.19~55 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=d44f0d03f175f6812650ec7c86cb3b3878667cae;p=gitmo%2FMouse.git Implement basic usage of "enum" type constraints --- diff --git a/lib/Mouse/Util/TypeConstraints.pm b/lib/Mouse/Util/TypeConstraints.pm index 44b0b38..885788a 100644 --- a/lib/Mouse/Util/TypeConstraints.pm +++ b/lib/Mouse/Util/TypeConstraints.pm @@ -7,7 +7,7 @@ use Carp (); use Scalar::Util qw/blessed looks_like_number openhandle/; our @EXPORT = qw( - as where message from via type subtype coerce class_type role_type + as where message from via type subtype coerce class_type role_type enum ); my %TYPE; @@ -161,6 +161,15 @@ sub typecast_constraints { return $value; } +sub enum { + my $name = shift; + my %is_valid = map { $_ => 1 } @_; + + subtype( + $name => where => sub { $is_valid{$_} } + ); +} + 1; __END__ diff --git a/t/041-enum.t b/t/041-enum.t new file mode 100644 index 0000000..731dcc1 --- /dev/null +++ b/t/041-enum.t @@ -0,0 +1,29 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Test::More tests => 8; +use Test::Exception; + +do { + package Shirt; + use Mouse; + use Mouse::Util::TypeConstraints 'enum'; + + enum 'Size' => qw(small medium large); + + has size => ( + is => 'rw', + isa => 'Size', + ); +}; + +ok(Shirt->new(size => 'small')); +ok(Shirt->new(size => 'medium')); +ok(Shirt->new(size => 'large')); + +throws_ok { Shirt->new(size => 'extra small') } qr/^Attribute \(size\) does not pass the type constraint because: Validation failed for 'Size' failed with value extra small/; +throws_ok { Shirt->new(size => 'Small') } qr/^Attribute \(size\) does not pass the type constraint because: Validation failed for 'Size' failed with value Small/; +throws_ok { Shirt->new(size => '') } qr/^Attribute \(size\) does not pass the type constraint because: Validation failed for 'Size' failed with value /; +throws_ok { Shirt->new(size => 'small ') } qr/^Attribute \(size\) does not pass the type constraint because: Validation failed for 'Size' failed with value small /; +throws_ok { Shirt->new(size => ' small') } qr/^Attribute \(size\) does not pass the type constraint because: Validation failed for 'Size' failed with value small/; +