1 |
package Frey::Config; |
2 |
use Moose::Role; |
3 |
|
4 |
use YAML qw/LoadFile/; |
5 |
use Hash::Merge qw/merge/; |
6 |
use Data::Dump qw/dump/; |
7 |
|
8 |
=head1 NAME |
9 |
|
10 |
Frey::Config - read configuration YAML files |
11 |
|
12 |
=head1 SYNOPSYS |
13 |
|
14 |
Foo::Bar->config->{'baz'} == 42 |
15 |
|
16 |
If C<etc/site_config.yml> or C<etc/config.yml> have: |
17 |
|
18 |
'Foo::Bar': |
19 |
baz: 42 |
20 |
|
21 |
or C<etc/Foo/Bar.yml> has |
22 |
|
23 |
baz: 42 |
24 |
|
25 |
You can also force config re-load with |
26 |
|
27 |
Foo::Bar->load_config('custom'); |
28 |
|
29 |
which will load C<etc/custom.yml> as most specific |
30 |
configuration. |
31 |
|
32 |
=cut |
33 |
|
34 |
our %config; |
35 |
|
36 |
sub load_config { |
37 |
my $self = shift; |
38 |
foreach my $name ( 'config', 'site_config', ref($self), @_ ) { |
39 |
my $path = "etc/$name.yml"; |
40 |
if ( $path =~ s{::}{/}g ) { |
41 |
# load under Package name |
42 |
%config = %{ merge( { ref($self) => LoadFile($path) }, \%config ) } if -e $path; |
43 |
} else { |
44 |
%config = %{ merge( LoadFile($path) , \%config ) } if -e $path; |
45 |
} |
46 |
warn "## $path current config = ",dump( %config ) if $self->debug; |
47 |
} |
48 |
} |
49 |
|
50 |
sub config { |
51 |
my $self = shift; |
52 |
my $key = shift || ref($self); |
53 |
warn "## config $key" if $self->debug; |
54 |
$self->load_config unless defined %config; |
55 |
#confess "$key doesn't exist in config" unless defined $config{ $key }; |
56 |
return unless defined $config{ $key }; |
57 |
return $config{ $key }; |
58 |
} |
59 |
|
60 |
1; |