views:

24

answers:

1

I'm currently working on a CLI app in Ruby, I'm using Trollop (http://trollop.rubyforge.org/) for dealing with cli arguments.

I'd also like to implement the possibility of storing the required options in ~/.mycfg as well as cwd/.mycfg, the latter taking precedence.

The behaviour I'm trying to implement is:

If .mycfg exists in the current working directory, load default options from there, otherwise, if it exists in the user's home directory, load options from there.

I will then override those options if they are also passed as arguments.

The question is, what format should the config file be in? I've thought about YAML, but then how to I merge the array that Trollop generates for the parameters with the YAML, or the other way around.

+1  A: 

One easy thing you can try is to modify ARGV before Trollop processes it. First, read in your config file and convert the data stored there into an array of equivalent command-line options. Now, prepend that array to ARGV and then set Trollop loose. That way, Trollop will parse all of your arguments (whether they came from the config file or from the CLI). Since your config file parameters are now listed before the CLI parameters, any CLI option will override a matching config file option (since later options override earlier options).

Your config file can be in any format you want to use, but sometimes the simplest form can be the easiest. Try a plain text format where the config file contents are simply the exact parameters that you want to pass to your script. That is to say, the contents of the file are written such that calling:

your_script.rb `cat optionsfile` -more -CLI -options

would work as expected. Storing options in this format makes them easy to edit and easy to process. Simply read in the file (should be a single line) and call String.split(' ') to split the options into an array, just like they would appear when coming from ARGV. A variation is to have a multi-line config file with one CLI parameter per line. In that case, you would build up your array of options one line at a time using something like File.each_line(configfile) {|x| options_array << x}.

bta
Perfect. Haven't thought of modifying ARGV, such a simple solution. Thanks!
Andrei Serdeliuc