12

I have a Moose class that is intended to be subclassed, and every subclass has to implement an "execute" method. However, I would like to put apply a method modifier to the execute method in my class, so that it applies to the execute method in all subclasses. But method modifiers are not preserved when a method is overriden. Is there any way to ensure that all subclasses of my class will have my method modifier applied to their execute methods?

Example: In a superclass, I have this:

before execute => sub {
    print "Before modifier is executing.\n"
}

Then, in a subclass of that:

sub execute {
    print "Execute method is running.\n"
}

When the execute method is called, it doesn't say anything about the "before" modifier.

Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159

1 Answers1

9

This is what the augment method modifier is made for. You can put this in your superclass:

sub execute {
  print "This runs before the subclass code";
  inner();
  print "This runs after the subclass code";
}

And then instead of allowing your subclasses to override execute directly, you have them augment it:

augment 'execute' => sub {
  print "This is the subclass method";
};

Basically it gives you functionality that's just like the around modifier, except with the parent/child relationship changed.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • 2
    Hmm. I forgot to mention that my superclass actually inherits from another non-Moose class that expects its subclasses to declare an execute method, so augment/inner won't work. But I agree that this is the solution in general. As for my specific problem, I found out that I could simply put my modifier on the method that *calls* execute, because that method is never redefined or overridden in subclasses. So I guess I'll mare this as accepted. – Ryan C. Thompson Feb 11 '11 at 05:09
  • @Ryan Thompson, I haven't tried this, I think you could put a nearly empty Moose class between your parent and children. Then put the `hobbs`' execute method into your Moose adapter-class, inherit everything else, and there you go. **Warning: untested, untried, poorly thought out ramblings of a groggy person--use with extreme caution.** – daotoad Feb 11 '11 at 17:11
  • 1
    @Ryan but the superclass *does* declare an execute method and it *is* a subclass of the class that expects its subclasses to declare an execute method, so all is kosher with augment/inner. Where in the tree the method is actually added *should* be irrelevant. – hobbs Feb 11 '11 at 22:23