Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to refactor some code to eliminate duplication, and am having trouble figuring out how to pass a config variable up to the superclass. I assume this should be simple....

My duplicated method is a 'begin()' that I'm overriding in order to set some specific logging functionality. Right now, it looks like this:

package MyApp::Foo; use namespace::autoclean; use Moose; # ... BEGIN { extends MyApp::Utilities; } # override begin method (fr Catalyst::Action::Deserialize) to access l +og stuff sub begin : Private { my ($self, $c) = @_; my $logfile = $c->config->{ 'foo_logfile'}; # This is stored in e +xternal config file; name isn't predictable my $log = Log::Dispatch->new( outputs => [ [ 'File', min_level => 'debug', mode => '>>', newline => 1, f +ilename => $logfile ], ], ); $c->stash->{log_object} = $log; $c->forward('deserialize'); # ultimately goes to our callback } sub deserialize : ActionClass('Deserialize') {}

All I want to do is move this into 'MyApp::Utilities', which already contains some generic stuff. The only thing that differs for each subclass is the name of the logfile. But I can't figure out how to tell the superclass this name. If I try '__PACKAGE__->config( logfile => 'foo_logfile' );' that fails because the 'extends' is called before this is read. If I try to move the '__PACKAGE__->config' into the 'BEGIN' block, that fails because it doesn't know about 'config()' at this point. What's my solution?

Replies are listed 'Best First'.
Re: Catalyst/Moose: passing specific config value to superclass
by Anonymous Monk on Oct 13, 2018 at 19:46 UTC

    (MyApp::Utilities itself extends Catalyst::Controller, btw.)

Re: Catalyst/Moose: passing specific config value to superclass
by trwww (Priest) on Oct 23, 2018 at 15:39 UTC

    I don't have any advice about your specific code, but I'd suggest moving your log setup outside of the request cycle. Any reason you're rolling your own instead of using any of the many catalyst logging utilities from CPAN? For example check out Log::Log4perl::Catalyst:

    https://metacpan.org/pod/Log::Log4perl::Catalyst