From: Cory Watson Date: Tue, 23 Feb 2010 20:05:41 +0000 (-0600) Subject: Add find_type_for method to Union. X-Git-Tag: 0.99~3 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=1aae641cb791e8160b5e6c8d7169460fbf31c9e6;p=gitmo%2FMoose.git Add find_type_for method to Union. --- diff --git a/Changes b/Changes index f63a51b..180b234 100644 --- a/Changes +++ b/Changes @@ -3,6 +3,11 @@ for, noteworthy changes. 0.99 ??? + [NEW FEATURES] + + * New method find_type_for in Moose::Meta::TypeConstraint::Union, for finding + which member of the union a given value validates for. (Cory Watson) + [NEW DOCUMENTATION] * Added Moose::Manual::Support that defines the support, compatiblity, and diff --git a/lib/Moose/Meta/TypeConstraint/Union.pm b/lib/Moose/Meta/TypeConstraint/Union.pm index 8cf2ca6..d21ae8b 100644 --- a/lib/Moose/Meta/TypeConstraint/Union.pm +++ b/lib/Moose/Meta/TypeConstraint/Union.pm @@ -7,6 +7,8 @@ use metaclass; use Moose::Meta::TypeCoercion::Union; +use List::Util qw(first); + our $VERSION = '0.98'; $VERSION = eval $VERSION; our $AUTHORITY = 'cpan:STEVAN'; @@ -93,6 +95,12 @@ sub validate { return ($message . ' in (' . $self->name . ')') ; } +sub find_type_for { + my ($self, $value) = @_; + + return first { $_->check($value) } @{ $self->type_constraints }; +} + sub is_a_type_of { my ($self, $type_name) = @_; foreach my $type (@{$self->type_constraints}) { @@ -197,6 +205,12 @@ messages returned by the member type constraints. A type is considered equal if it is also a union type, and the two unions have the same member types. +=item B<< $constraint->find_type_for($value) >> + +This returns the first member type constraint for which C is +true, allowing you to determine which of the Union's member type constraints +a given value matches. + =item B<< $constraint->is_a_type_of($type_name_or_object) >> This returns true if any of the member type constraints return true diff --git a/t/040_type_constraints/008_union_types.t b/t/040_type_constraints/008_union_types.t index cff7248..9dc3ece 100644 --- a/t/040_type_constraints/008_union_types.t +++ b/t/040_type_constraints/008_union_types.t @@ -30,6 +30,10 @@ ok($Str_or_Undef->check('String'), '... (Str | Undef) can accept a String value' ok($Str_or_Undef->is_a_type_of($Str), "subtype of Str"); ok($Str_or_Undef->is_a_type_of($Undef), "subtype of Undef"); +cmp_ok($Str_or_Undef->find_type_for('String'), 'eq', 'Str', 'find_type_for Str'); +cmp_ok($Str_or_Undef->find_type_for(undef), 'eq', 'Undef', 'find_type_for Undef'); +ok(!defined($Str_or_Undef->find_type_for(sub { })), 'no find_type_for CodeRef'); + ok( !$Str_or_Undef->equals($Str), "not equal to Str" ); ok( $Str_or_Undef->equals($Str_or_Undef), "equal to self" ); ok( $Str_or_Undef->equals(Moose::Meta::TypeConstraint::Union->new(type_constraints => [ $Str, $Undef ])), "equal to clone" );