Is it possible to pass regex to isa () using Moose based objects?

Can I use isa in Moose with a regex as a parameter? If this is not possible, can I achieve the same as with anything other than ->isa ?

ok having the following types Animal::Giraffe , Animal::Carnivore::Crocodile , I want to do ->isa(/^Animal::/) , can I do this? if I can’t, what can I use to achieve the desired effect?

+4
source share
4 answers

These related types must "fulfill" the same role as Animal. Then you can write:

 has 'animal' => ( is => 'ro', does => 'Animal', required => 1, ); 

Now you have something much more reliable than regular expression to ensure the consistency of your program.

+8
source

Leon Timmerman's answer was close to what I suggest, although I would use sugar from Moose :: Util :: TypeConstraints

 use Moose; use Moose::Util::TypeConstraints; subtype Animal => as Object => where { blessed $_ =~ /^Animal::/ }; has animal => ( is => 'rw', isa => 'Animal' ); 
+4
source

Extending perigrin's answer so that it works if the class has Animal::* anywhere in its superclasses, and not just in its closest class name (for example, if Helper::Monkey isa Animal::Monkey ):

 use Moose; use Moose::Util::TypeConstraints; subtype Animal => as Object => where { grep /^Animal::/, $_->meta->linearized_isa }; has animal => ( is => 'rw', isa => 'Animal' ); 

I think the jrockway proposal to use the role instead has many advantages, but if you want to go that route, you can also cover all the bases.

+3
source

I think this should do it.

 use Moose; use Moose::Util::TypeConstraints; my $animal = Moose::Meta::TypeConstraint->new( constraint => sub { $_[0] =~ /^Animal::/} ); has animal => (is => 'rw', isa => $animal); 

ETA: I agree with jrockway: if you have no convincing reason, you just have to use inheritance.

+1
source

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


All Articles