Search code examples
perlmoose

How can a Moose attribute 'does' a Mouse role?


I have a Moose class which composes a Mouse role.

package My::Moose::Class;
use Moose;
has 'mouse_obj' => (
    is   => 'ro',
    does => 'NotMy::Mouse::Role',
);

package NotMy::Mouse::Role;
use Mouse::Role;

package NotMy::Mouse::Class;
use Mouse;
with 'NotMy::Mouse::Role';

And this will get an error because the Mouse role is not recognised as a type in Moose:

my $f = My::Moose::Class->new( mouse_obj => NotMy::Mouse::Class->new );

Attribute (mouse_obj) does not pass the type constraint because: Validation failed for 'NotMy::Mouse::Role' with value NotMy::Mouse::Class=HASH(0x23932dc) (not isa NotMy::Mouse::Role) at ...

What are some ways to get this working without changing the Mouse objects over to Moose?


Solution

  • One way you could do this is make a custom type constraint that does the check you want.

    use Moose::Util::TypeConstraints;
    
    subtype 'MouseRole'
        => as 'Object'
        => where sub { $_->does('NotMy::Mouse::Role') };
    
    has 'mouse_obj' => (
        is   => 'ro',
        isa => 'MouseRole', # "isa" not "does"!
    );