How to override sub in Moose :: Role?

I am trying to implement the Moose :: Role class, which behaves like an abstract class in Java. I would like to implement some methods in Role, but then be able to redefine these methods in specific classes. If I try this using the same style that works when I extend classes, I get a Cannot add an override method if a local method is already present error. Here is an example:

My abstract class:

 package AbstractClass; use Moose::Role; sub my_ac_sub { my $self = shift; print "In AbstractClass!\n"; return; } 1; 

My specific class:

 package Class; use Moose; with 'AbstractClass'; override 'my_ac_sub' => sub { my $self = shift; super; print "In Class!\n"; return; }; __PACKAGE__->meta->make_immutable; 1; 

And then:

 use Class; my $class = Class->new; $class->my_ac_sub; 

Am I doing something wrong? Is what I'm trying to do differently? Am I not trying to do this at all?

+6
source share
2 answers

Turns out I used it incorrectly. I opened a ticket and the correct way to do this was shown:

 package Class; use Moose; with 'AbstractClass'; around 'my_ac_sub' => sub { my $next = shift; my $self = shift; $self->$next(); print "In Class!\n"; return; }; __PACKAGE__->meta->make_immutable; 1; 

Making this change has the desired effect.

+4
source

Some time ago , I did this by performing a role consisting entirely of requires statements. This forms an abstract base class. Then you can put your default implementations in another class and inherit from this:

 #!/usr/bin/env perl use 5.014; package AbstractClass; use Moose::Role; requires 'my_virtual_method_this'; requires 'my_virtual_method_that'; package DefaultImpl; use Moose; with 'AbstractClass'; sub my_virtual_method_this { say 'this'; } sub my_virtual_method_that { say 'that' } package MyImpl; use Moose; extends 'DefaultImpl'; with 'AbstractClass'; override my_virtual_method_that => sub { super; say '... and the other'; }; package main; my $x = MyImpl->new; $x->my_virtual_method_this; $x->my_virtual_method_that; 

If you want to provide standard implementations for only a few methods, define in the role, remove requires from DefaultImpl .

Output:

  $ ./zpx.pl
 this
 that
 ... and the other 
+2
source

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


All Articles