1 package MooseX::ConfigFromFile;
4 use MooseX::Types::Path::Class qw( File );
8 requires 'get_config_from_file';
14 predicate => 'has_configfile',
18 my ($class, %opts) = @_;
20 if($opts{configfile}) {
21 %opts = (%{$class->get_config_from_file($opts{configfile})}, %opts);
34 MooseX::ConfigFromFile - An abstract Moose role for setting attributes from a configfile
39 ## A real role based on this abstract role:
42 package MooseX::SomeSpecificConfigRole;
45 with 'MooseX::ConfigFromFile';
47 use Some::ConfigFile::Loader ();
49 sub get_config_from_file {
50 my ($class, $file) = @_;
52 my $options_hashref = Some::ConfigFile::Loader->load($file);
54 return $options_hashref;
59 ## A class that uses it:
63 with 'MooseX::SomeSpecificConfigRole';
65 # ... insert your stuff here ...
68 ## A script that uses the class with a configfile
71 my $obj = Foo->new_with_config(configfile => '/etc/foo.yaml', other_opt => 'foo');
75 This is an abstract role which provides an alternate constructor for creating
76 objects using parameters passed in from a configuration file. The
77 actual implementation of reading the configuration file is left to
80 It declares an attribute C<configfile> and a class method C<new_with_config>,
81 and requires that concrete roles derived from it implement the class method
82 C<get_config_from_file>.
84 L<MooseX::Getopt> knows about this abstract role, and will use it if available
85 to load attributes from the file specified by the commandline flag C<--configfile>
86 during its normal C<new_with_options>.
92 This is a L<Path::Class::File> object which can be coerced from a regular pathname
93 string. This is the file your attributes are loaded from.
97 =head2 new_with_config
99 This is an alternate constructor, which knows to look for the C<configfile> option
100 in its arguments and use that to set attributes. It is much like L<MooseX::Getopts>'s
101 C<new_with_options>. Example:
103 my $foo = SomeClass->new_with_config(configfile => '/etc/foo.yaml');
105 Explicit arguments will overide anything set by the configfile.
107 =head2 get_config_from_file
109 This class method is not implemented in this role, but it is required of all subroles.
110 Its two arguments are the classname and the configfile, and it is expected to return
111 a hashref of arguments to pass to C<new()>.
115 The Moose meta stuff, included here because otherwise pod tests fail sometimes
121 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
125 This library is free software; you can redistribute it and/or modify
126 it under the same terms as Perl itself.