6214934c2ae862af0699a29896b4f83b0bb240fb
[gitmo/MooseX-ConfigFromFile.git] / lib / MooseX / ConfigFromFile.pm
1 package MooseX::ConfigFromFile;
2
3 use Moose::Role;
4 use MooseX::Types::Path::Tiny 'Path';
5 use MooseX::Types::Moose 'Undef';
6 use Try::Tiny;
7 use Carp qw(croak);
8 use namespace::autoclean;
9
10 requires 'get_config_from_file';
11
12 # overridable in consuming class or role to provide a default value
13 # This is called before instantiation, so it must be a class method,
14 # and not depend on any other attributes
15 sub _get_default_configfile { }
16
17 has configfile => (
18     is => 'ro',
19     isa => Path|Undef,
20     coerce => 1,
21     predicate => 'has_configfile',
22     do { try { require MooseX::Getopt; (traits => ['Getopt']) } },
23     lazy => 1,
24     # it sucks that we have to do this rather than using a builder, but some old code
25     # simply swaps in a new default sub into the attr definition
26     default => sub { shift->_get_default_configfile },
27 );
28
29 sub new_with_config {
30     my ($class, %opts) = @_;
31
32     my $configfile;
33
34     if(defined $opts{configfile}) {
35         $configfile = $opts{configfile}
36     }
37     else {
38         # This would only succeed if the consumer had defined a new configfile
39         # sub to override the generated reader - as suggested in old
40         # documentation
41         $configfile = try { $class->configfile };
42
43         # this is gross, but since a lot of users have swapped in their own
44         # default subs, we have to keep calling it rather than calling a
45         # builder sub directly - and it might not even be a coderef either
46         my $cfmeta = $class->meta->find_attribute_by_name('configfile');
47         $configfile = $cfmeta->default if not defined $configfile and $cfmeta->has_default;
48
49         if (ref $configfile eq 'CODE') {
50             $configfile = $configfile->($class);
51         }
52
53         my $init_arg = $cfmeta->init_arg;
54         $opts{$init_arg} = $configfile if defined $configfile and defined $init_arg;
55     }
56
57     if (defined $configfile) {
58         my $hash = $class->get_config_from_file($configfile);
59
60         no warnings 'uninitialized';
61         croak "get_config_from_file($configfile) did not return a hash (got $hash)"
62             unless ref $hash eq 'HASH';
63
64         %opts = (%$hash, %opts);
65     }
66
67     $class->new(%opts);
68 }
69
70 no Moose::Role; 1;
71
72 __END__
73
74 =pod
75
76 =head1 NAME
77
78 MooseX::ConfigFromFile - An abstract Moose role for setting attributes from a configfile
79
80 =head1 SYNOPSIS
81
82   ########
83   ## A real role based on this abstract role:
84   ########
85
86   package MooseX::SomeSpecificConfigRole;
87   use Moose::Role;
88
89   with 'MooseX::ConfigFromFile';
90
91   use Some::ConfigFile::Loader ();
92
93   sub get_config_from_file {
94     my ($class, $file) = @_;
95
96     my $options_hashref = Some::ConfigFile::Loader->load($file);
97
98     return $options_hashref;
99   }
100
101
102   ########
103   ## A class that uses it:
104   ########
105   package Foo;
106   use Moose;
107   with 'MooseX::SomeSpecificConfigRole';
108
109   # optionally, default the configfile:
110   sub _get_default_configfile { '/tmp/foo.yaml' }
111
112   # ... insert your stuff here ...
113
114   ########
115   ## A script that uses the class with a configfile
116   ########
117
118   my $obj = Foo->new_with_config(configfile => '/etc/foo.yaml', other_opt => 'foo');
119
120 =head1 DESCRIPTION
121
122 This is an abstract role which provides an alternate constructor for creating
123 objects using parameters passed in from a configuration file.  The
124 actual implementation of reading the configuration file is left to
125 concrete sub-roles.
126
127 It declares an attribute C<configfile> and a class method C<new_with_config>,
128 and requires that concrete roles derived from it implement the class method
129 C<get_config_from_file>.
130
131 Attributes specified directly as arguments to C<new_with_config> supersede those
132 in the configfile.
133
134 L<MooseX::Getopt> knows about this abstract role, and will use it if available
135 to load attributes from the file specified by the command line flag C<--configfile>
136 during its normal C<new_with_options>.
137
138 =head1 Attributes
139
140 =head2 configfile
141
142 This is a L<Path::Tiny> object which can be coerced from a regular path
143 string or any object that supports stringification.
144 This is the file your attributes are loaded from.  You can add a default
145 configfile in the consuming class and it will be honored at the appropriate
146 time; see below at L</_get_default_configfile>.
147
148 If you have L<MooseX::Getopt> installed, this attribute will also have the
149 C<Getopt> trait supplied, so you can also set the configfile from the
150 command line.
151
152 =head1 Class Methods
153
154 =head2 new_with_config
155
156 This is an alternate constructor, which knows to look for the C<configfile> option
157 in its arguments and use that to set attributes.  It is much like L<MooseX::Getopts>'s
158 C<new_with_options>.  Example:
159
160   my $foo = SomeClass->new_with_config(configfile => '/etc/foo.yaml');
161
162 Explicit arguments will override anything set by the configfile.
163
164 =head2 get_config_from_file
165
166 This class method is not implemented in this role, but it is required of all
167 classes or roles that consume this role.
168 Its two arguments are the class name and the configfile, and it is expected to return
169 a hashref of arguments to pass to C<new()> which are sourced from the configfile.
170
171 =head2 _get_default_configfile
172
173 This class method returns nothing by default, but can and should be redefined
174 in a consuming class to return the default value of the configfile (if not
175 passed into the constructor explicitly).
176
177 =head1 COPYRIGHT
178
179 Copyright (c) - the MooseX::ConfigFromFile "AUTHOR" and "CONTRIBUTORS" as listed below.
180
181 =head1 AUTHOR
182
183 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
184
185 =head1 CONTRIBUTORS
186
187 =over
188
189 =item Tomas Doran
190
191 =item Karen Etheridge
192
193 =item Chris Prather
194
195 =item Zbigniew Lukasiak
196
197 =back
198
199 =head1 LICENSE
200
201 This library is free software; you can redistribute it and/or modify
202 it under the same terms as Perl itself.
203
204 =cut