Amon2でMODE共用のconfigファイルを読み込んで使う。
2014年11月26日
Amon2は、configをdevelopmentとproductionの読み替えができるんで、DB接続周りとかの変更が可能なんですが、その他の部分で同じ内容がいくつかあって、いちいちconfigを全部変えるがめんどいので、共通な内容は別のconfigファイル(どのMODEでも読み込まれる共用ファイル)にしとこうと思います。
package MyApp;
use parent qw/Amon2/;
use Amon2::Config::Simple;
use FindBin;
use Path::Class;
sub load_config {
my $self = shift;
my $base_dir = "$FindBin::Bin/../config/share";
# 通常のconfig(development.plとか、production.plとか)
my $config = Amon2::Config::Simple->load($self, +{ environment => $ENV{RUN_MODE} });
my $share_config = {};
# config/share/以下のファイルを全部処理
dir($base_dir)->recurse(
callback => sub {
my $file = shift; # フルパス /home/user/myapp/config/share/xxxxxx.pl
if ( $file =~ /\/(\w+?)\.pl$/ ) {
my $class = $1; # ファイル名を取得
my $fname = File::Spec->catfile( $file );
my $share = do $fname;
Carp::croak("$fname: $@") if $@;
Carp::croak("$fname: $!") unless defined $share;
unless ( ref($config) eq 'HASH' ) {
Carp::croak("$fname does not return HashRef.");
}
$share_config->{ $class } = $share;
}
}
);
# configに追加
$config->{'share'} = $share_config;
return $config;
}
Path::Classを使って、config/share/以下のファイルを探す。
ファイルを読み込む部分は、Amon2::Config::Simpleほぼそのままコピペ。
複数のconfigファイルを置いたとしても、全部読み込まれる。
config/share/****.pl config/share/****.pl config/share/****.pl
例えば、config/share/hogehoge.plを追加した場合は、
#$c->config->{'share'}->{ファイル名}->{中身}
$c->config->{'share'}->{'hogehoge'}
みたいな感じでコントローラーからアクセスできる。