Testing the role of Elk in non Moose

let's say you have a Moose class that requires an attribute that fulfills the role:

package MyMooseClass;
use Moose;

has 'a' => ( does => 'MyRole' );

Now I would like to create an instance of MyMooseClass as follows:

my $instance = MyMooseClass->new( { a => $a_non_moose_stuff } );

Where $ a_non_moose_stuff is an instance of the non-moose class, but implements the required role methods.

Is there a way to get Moose to check that my $ a_non_moose_stuff matches the role, even if it is not implemented using Moose?

+3
source share
1 answer

The easiest way is to use duck_type instead of a role to test your interface. Duck_type is a looser restriction, basically duck_type is just a list of methods that objects are expected to have. For instance:

package MyMooseClass;
use Moose;
use Moose::Util::TypeConstraints qw/duck_type/;

has 'a' => (
  isa => duck_type(qw/method1 method1 some_other_method/),
);

Moose::Util::TypeConstraints , duck_type. .

, , . MooseX::Types.

, Hash Reference , Moose , Moose, , . , :

my $instance = MyClass->new(param1=>'val1', param2=>'val2');

Hash Reference , , , Moose Perl. Moose , , -, , . .

,

+5

Source: https://habr.com/ru/post/1762425/


All Articles