From: gfx Date: Wed, 9 Dec 2009 05:34:33 +0000 (+0900) Subject: Improve enum to accept "enum($name, $arrayref)" construction X-Git-Tag: 0.44~11 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=gitmo%2FMouse.git;a=commitdiff_plain;h=f152b0997e523b60b2dbcefff8d102fc1096bf49;hp=ec0ef2581f45f3569dc4344a19d88b698a33f3d9 Improve enum to accept "enum($name, $arrayref)" construction --- diff --git a/lib/Mouse/Util/TypeConstraints.pm b/lib/Mouse/Util/TypeConstraints.pm index 6672030..2b2d558 100644 --- a/lib/Mouse/Util/TypeConstraints.pm +++ b/lib/Mouse/Util/TypeConstraints.pm @@ -184,16 +184,12 @@ sub typecast_constraints { # DEPRECATED sub enum { my($name, %valid); - # enum ['small', 'medium', 'large'] - if (ref($_[0]) eq 'ARRAY') { - %valid = map{ $_ => undef } @{ $_[0] }; - $name = sprintf '(%s)', join '|', sort @{$_[0]}; - } - # enum size => 'small', 'medium', 'large' - else{ - $name = shift; - %valid = map{ $_ => undef } @_; + if(!(@_ == 1 && ref($_[0]) eq 'ARRAY')){ + $name = shift; } + + %valid = map{ $_ => undef } (@_ == 1 && ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_); + return _create_type 'type', $name => ( optimized_as => sub{ defined($_[0]) && !ref($_[0]) && exists $valid{$_[0]} }, diff --git a/t/001_mouse/041-enum.t b/t/001_mouse/041-enum.t index 5546f4f..8dfe9b9 100644 --- a/t/001_mouse/041-enum.t +++ b/t/001_mouse/041-enum.t @@ -1,7 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; -use Test::More tests => 16; +use Test::More tests => 19; use Test::Exception; do { @@ -38,3 +38,11 @@ for my $class ('Shirt', 'Shirt::Anon') { throws_ok { $class->new(size => ' small') } qr/^Attribute \(size\) does not pass the type constraint because: Validation failed for '\S+' failed with value small/; } +use Mouse::Util::TypeConstraints qw(enum); + +my $t = enum 'Foo', [qw(foo bar)]; + +ok $t->check('foo'), 'enum $name, $array_ref'; +ok $t->check('bar'); +ok!$t->check('baz'); +