Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support | overload to work better with MooseX::Types #156

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions lib/Moose/Meta/TypeConstraint.pm
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,29 @@ use warnings;
use metaclass;

use overload '0+' => sub { refaddr(shift) }, # id an object
'|' => sub {

## It's kind of ugly that we need to know about Union Types, but this
## is needed for syntax compatibility. Maybe someday we'll all just do
## Or[Str,Str,Int]

my @args = @_[0,1]; ## arg 3 is special, see the overload docs.
my @tc = grep {blessed $_} map {
blessed $_ ? $_ :
Moose::Util::TypeConstraints::find_or_parse_type_constraint($_)
|| __PACKAGE__->_throw_error( "$_ is not a type constraint")
} @args;

( scalar @tc == scalar @args)
|| __PACKAGE__->_throw_error(
"one of your type constraints is bad. Passed: ". join(', ', @args) ." Got: ". join(', ', @tc));

( scalar @tc >= 2 )
|| __PACKAGE__->_throw_error("You must pass in at least 2 type names to make a union");

my $union = Moose::Meta::TypeConstraint::Union->new(type_constraints=>\@tc);
return Moose::Util::TypeConstraints::register_type_constraint($union);
},
'""' => sub { shift->name }, # stringify to tc name
bool => sub { 1 },
fallback => 1;
Expand Down
56 changes: 56 additions & 0 deletions t/type_constraints/union_overload_or.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use strict;
use warnings;

use Test::Fatal;
use Test::More;

{

package Duck;
use Moose;

sub quack { }

}

{

package Swan;
use Moose;

sub honk { }

}

{

package RubberDuck;
use Moose;

sub quack { }

}


use Moose::Util::TypeConstraints 'class_type';

my $union = class_type('Duck') | class_type('RubberDuck');

my $duck = Duck->new();
my $rubber_duck = RubberDuck->new();
my $swan = Swan->new();

my @domain_values = ( $duck, $rubber_duck );
is(
exception { $union->assert_valid($_) },
undef,
qq{Union accepts "$_".}
) for @domain_values;

like(
exception { $union->assert_valid($swan) },
qr/Validation failed for/,
qq{Union does not accept Swan.}
);
done_testing;