You may have some scripts related to your Catalyst application and you would like to re-use pieces of the application's configuration information. For example, database connection information is something that could be used in a Catalyst application, but also one could use the connection info within command line scripts so they too can get at the underlying data model. This petit paper examines the use of Config::JFDI and Config::General to get at the Catalyst .conf file.
Example .conf
Here is an example of a .conf file with file path information that I'd like to have access to from a script.
name YoApp home /home/apps/YoApp data_dir __path_to(data)__ weather_dir /var/www/weather/images slashdot_rss $data_dir/slashdot.rss freshmeat_xml $data_dir/freshmeat.xml perl_blogs_file $data_dir/perl_blogs.dat cpan_modules_file $data_dir/recent_cpan_modules.dat med_menu_rss $data_dir/med_menu.rss snotel_db_file $data_dir/snotel.db precip_forecast_file $weather_dir/precip-forecast.png temperature_forecast_file $weather_dir/temperature-forecast.png
Note that we set the home directory explicitly. While Catalyst can find the home directory based on the standard Catalyst application file structure, a script needs a full path if it's to be called from random directories.
Get the config
The key to getting at the config from a script will be the use of Config::JFDI. Let's create a baby module that has a routine to return the config information. We'll call this routine later from our script.
package GetConfig;
use Config::JFDI;
use Dir::Self;
sub get_config {
my $jfdi = Config::JFDI->new(
name => 'YoApp',
path => __DIR__ . "/..",
driver => {
'General' => { -InterPolateVars => 1 }
});
my $config = $jfdi->get;
return $config;
}
1
NOTES:
* We must tell Config::JFDI both the name and the location of the conf file. We give it a path relative to the module's position which is assumed to be in YoApp/lib.
* For Config::General to interpolate variables we pass the 'InterPolateVars' option. This allows us to have $data_dir variable interpolated to its full path within the .conf file.
Using it.
Now that we have the .conf file defined and method to get at its contents, let's use it.
use FindBin qw($Bin);
use lib "$Bin/../lib";
use GetConfig;
my $config = GetConfig::get_config();
my $storage_file = $config->{perl_blogs_file};
Here we make sure the lib/ with GetConfig.pm is in our @INC. Then we just call the get_config() function which returns the config contents as a hash reference. If we want the value of a particular configuration variable (key) then we just pass the key as we do for the perl blogs data file above.
Conclusion
Config::JFDI combined with Config::General provide a nice way to separate configuration information from a Catalyst application so it can be re-used elsewhere such as a command line script.




Leave a comment
All comments are moderated. Spammers don't waste your time