Extending with Moose

xsawyerx on 2008-12-22T15:47:29

I need to extend a POE module and add some crucial functionality in order to use it in an enterprise production environment. Using Moose for this makes it so easy I'm willing to give up the extra few seconds it takes for compilation.

Basically it took me a while to figure out how I want to extend it. I thought about adding a file to the project and repackage it as a distribution (obviously wouldn't go up on CPAN in that way) but that was too much work (Perl programmers like to be lazy). Then I thought about hacking the source directly but that's a given "no no". Alright, so hmm.. I can easily override a function, replicate it and then add/change it accordingly. This, however, isn't a good idea. Whenever you have to copy stuff, you've probably made a design error.

Fortunately, Moose lets me just add code at the end of a function. Works like this:

use YAML qw( LoadFile );
use Moose;
extends 'Whatever';

after '_something' => sub { my $self = shift;

if ( my $yaml_conf = $self->{'yaml_conf'} ) { $self->{'yaml_data'} = LoadFile($yaml_conf); } };