I needed to read a Mojo app's config file without being in the Mojo app itself. If I were using YAML or JSON that wouldn't be a problem, but I was using the old-school Perl code format.
I pulled some of the stuff out of Mojolicious::Plugin::Config to write a little script to do it the same way. One thing to note is that mode-specific config files (app.development.conf) overlay the main one rather than merging into it. A later config key at the top level completely replaces the one before it, just as we expect from a Perl hash.
This is also on Reddit.
sub load { $_[0]->parse(decode('UTF-8', path($_[1])->slurp), @_[1, 2, 3]) }
sub parse {
my ($self, $content, $file, $conf, $app) = @_;
# Run Perl code in sandbox
my $config = eval 'package Mojolicious::Plugin::Config::Sandbox; no warnings;'
. "sub app; local *app = sub { \$app }; use Mojo::Base -strict; $content";
die qq{Can't load configuration from file "$file": $@} if $@;
die qq{Configuration file "$file" did not return a hash reference} unless ref $config eq 'HASH';
return $config;
}
my @files = qw(
app.conf
app.development.conf
);
# load files in order
my $config = {};
foreach my $file ( grep { -e } @file ) {
my $contents = decode( 'UTF-8', Mojo::File->new($file)->slurp );
my $this = eval <<~"HERE";
package Local::Sandbox;
no warnings;
$content;
HERE
$config = { $config->%*, $this->%* };
}
say Mojo::Util::dumper($config);