I'd like store variables in a configuration file so that I can just set them in one place and access them whenever needed.
Where is the place to put such variables in a Dancer app, and how do I access them?
The best way is to have one config.yml file with default global settings, like the following:
# appdir/config.yml
logger: 'file'
layout: 'main'
Your Question: How to access?
Ans: A Dancer application can use the 'config' keyword to easily access the settings within its config file, for instance:
get '/appname' => sub {
return "This is " . config->{appname};
};
This makes keeping your application's settings all in one place simple and easy - you shouldn't need to worry about implementing all that yourself.
You may well want to access your webapp's configuration from outside your webapp. Using Dancer, you can use the values from config.yml and some additional default values:
# bin/script1.pl
use Dancer ':script';
print "template:".config->{template}."\n"; #simple
print "log:".config->{log}."\n"; #undef
Note that config->{log}
should result undef error on a default scaffold since you did not load the environment and in the default scaffold log is defined in the environment and not in config.yml. Hence undef
.
If you want to load an environment you need to tell Dancer where to look for it. One way to do so, is to tell Dancer where the webapp lives. From there Dancer deducts where the config.yml file is (typically $webapp/config.yml).
# bin/script2.pl
use FindBin;
use Cwd qw/realpath/;
use Dancer ':script';
#tell the Dancer where the app lives
my $appdir=realpath( "$FindBin::Bin/..");
Dancer::Config::setting('appdir',$appdir);
Dancer::Config::load();
#getter
print "environment:".config->{environment}."\n"; #development
print "log:".config->{log}."\n"; #value from development environment
By default Dancer loads development environment (typically $webapp/environment/development.yml). If you want to load an environment other than the default, try this:
# bin/script2.pl
use Dancer ':script';
#tell the Dancer where the app lives
Dancer::Config::setting('appdir','/path/to/app/dir');
#which environment to load
config->{environment}='production';
Dancer::Config::load();
#getter
print "log:".config->{log}."\n"; #has value from production environment