Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a sub in a Moose::Role?

Tags:

perl

moose

I'm trying to implement a Moose::Role class that behaves like an abstract class would in Java. I'd like to implement some methods in the Role, but then have the ability to override those methods in concrete classes. If I try this using the same style that works when I extend classes I get the error Cannot add an override method if a local method is already present. Here's an example:

My abstract class:

package AbstractClass;

use Moose::Role;

sub my_ac_sub {

    my $self = shift;

    print "In AbstractClass!\n";
    return;
}

1;

My concrete 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 accomplish supposed to be done a different way? Is what I'm trying to do not supposed to be done at all?

like image 293
Joel Avatar asked Sep 23 '13 12:09

Joel


1 Answers

Turns out I was using it incorrectly. I opened a ticket and was shown the correct way of doing this:

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.

like image 64
Joel Avatar answered Nov 03 '22 23:11

Joel