use Moose::Role;
use MooseX::Types::Path::Class qw( File );
+use Try::Tiny qw/ try /;
+use Carp qw(croak);
+use namespace::autoclean;
-our $VERSION = '0.02';
+our $VERSION = '0.04';
requires 'get_config_from_file';
predicate => 'has_configfile',
);
+# overridable in consuming class or role to provide a default value
+# called before instantiation, so must be a class method!
+sub _get_default_configfile { }
+
sub new_with_config {
my ($class, %opts) = @_;
$configfile = $opts{configfile}
}
else {
- my $cfmeta = $class->meta->get_attribute('configfile');
- $configfile = $cfmeta->default if $cfmeta->has_default;
+ # This would only succeed if the consumer had changed the name of the
+ # reader method, and defined a new configfile sub in its place
+ $configfile = try { to_File($class->configfile) };
+
+ # this is gross, but since a lot of users have swapped in their own
+ # default subs, we have to keep calling it rather than calling a
+ # builder sub directly - and it might not even be a coderef either
+ my $cfmeta = $class->meta->find_attribute_by_name('configfile');
+ $configfile ||= $cfmeta->default;
+
+ if (ref $configfile eq 'CODE') {
+ $configfile = $configfile->($class);
+ }
+
+ $configfile ||= $class->_get_default_configfile;
+
+ $opts{$cfmeta->init_arg} = $configfile if defined $configfile;
}
- if(defined $configfile) {
- %opts = (%{$class->get_config_from_file($configfile)}, %opts);
+ if (defined $configfile) {
+ my $hash = $class->get_config_from_file($configfile);
+
+ no warnings 'uninitialized';
+ croak "get_config_from_file($configfile) did not return a hash (got $hash)"
+ unless ref $hash eq 'HASH';
+
+ %opts = (%$hash, %opts);
}
$class->new(%opts);
with 'MooseX::SomeSpecificConfigRole';
# optionally, default the configfile:
- has +configfile ( default => '/tmp/foo.yaml' );
+ sub configfile { '/tmp/foo.yaml' }
# ... insert your stuff here ...
has +configfile ( default => '/etc/myapp.yaml' );
+Note that you can alternately just provide a C<configfile> method which returns
+the config file when called - this will be used in preference to the default of
+the attribute.
+
=head1 Class Methods
=head2 new_with_config
Its two arguments are the classname and the configfile, and it is expected to return
a hashref of arguments to pass to C<new()> which are sourced from the configfile.
-=head2 meta
+=head1 COPYRIGHT
-The Moose meta stuff, included here because otherwise pod tests fail sometimes
-
-=head1 BUGS
+Copyright (c) 2007 - 2009 the MooseX::ConfigFromFile "AUTHOR" and "CONTRIBUTORS" as listed below.
=head1 AUTHOR
Brandon L. Black, E<lt>blblack@gmail.comE<gt>
+=head1 CONTRIBUTORS
+
+=over
+
+=item Tomas Doran C<< <bobtfish@bobtfish.net> >> (current maintainer).
+
+=item Karen Etheridge
+
+=item Chris Prather
+
+=item Zbigniew Lukasiak
+
+=back
+
=head1 LICENSE
This library is free software; you can redistribute it and/or modify