1 package MooseX::SimpleConfig;
4 with 'MooseX::ConfigFromFile';
10 sub get_config_from_file {
11 my ($class, $file) = @_;
13 my $can_config_any_args = $class->can('config_any_args');
14 my %args = $can_config_any_args ?
15 ( %{$can_config_any_args->($class, $file)}, files => [ $file ], use_ext => 1 ) :
16 ( files => [ $file ], use_ext => 1 )
18 my $raw_cfany = Config::Any->load_files(\%args);
20 die q{Specified configfile '} . $file
21 . q{' does not exist, is empty, or is not readable}
22 unless $raw_cfany->[0]
23 && exists $raw_cfany->[0]->{$file};
25 my $raw_config = $raw_cfany->[0]->{$file};
27 die "configfile must represent a hash structure"
28 unless $raw_config && ref $raw_config && ref $raw_config eq 'HASH';
41 MooseX::SimpleConfig - A Moose role for setting attributes from a simple configfile
45 ## A YAML configfile named /etc/my_app.yaml:
53 with 'MooseX::SimpleConfig';
55 has 'foo' => (is => 'ro', isa => 'Str', required => 1);
56 has 'baz' => (is => 'rw', isa => 'Int', required => 1);
58 # ... rest of the class here
65 my $app = My::App->new_with_config(configfile => '/etc/my_app.yaml');
66 # ... rest of the script here
69 ###### combined with MooseX::Getopt:
75 with 'MooseX::SimpleConfig';
76 with 'MooseX::Getopt';
78 has 'foo' => (is => 'ro', isa => 'Str', required => 1);
79 has 'baz' => (is => 'rw', isa => 'Int', required => 1);
81 # ... rest of the class here
88 my $app = My::App->new_with_options();
89 # ... rest of the script here
91 ## on the command line
92 % perl my_app_script.pl -configfile /etc/my_app.yaml -otherthing 123
96 This role loads simple configfiles to set object attributes. It
97 is based on the abstract role L<MooseX::ConfigFromFile>, and uses
98 L<Config::Any> to load your configfile. L<Config::Any> will in
99 turn support any of a variety of different config formats, detected
100 by the file extension. See L<Config::Any> for more details about
103 Like all L<MooseX::ConfigFromFile> -derived configfile loaders, this
104 module is automatically supported by the L<MooseX::Getopt> role as
105 well, which allows specifying C<-configfile> on the commandline.
111 Provided by the base role L<MooseX::ConfigFromFile>. You can
112 provide a default configfile pathname like so:
114 has +configfile ( default => '/etc/myapp.yaml' );
118 =head2 new_with_config
120 Provided by the base role L<MooseX::ConfigFromFile>. Acts just like
121 regular C<new()>, but also accepts an argument C<configfile> to specify
122 the configfile from which to load other attributes. Explicit arguments
123 to C<new_with_config> will override anything loaded from the configfile.
125 =head2 get_config_from_file
127 Called internally by either C<new_with_config> or L<MooseX::Getopt>'s
128 C<new_with_options>. Invokes L<Config::Any> to parse C<configfile>.
132 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
136 This library is free software; you can redistribute it and/or modify
137 it under the same terms as Perl itself.