Reputation: 432
I have a standalone ruby script that is intended to be run from a commandline.
Currently I have a section to define stuff like paths to files and such.
key_path = "C:\\OpenSSL-Win64\\keys\\"
consumer_file = "henrb028.consumer"
key_file = "henrb028.key"
I'd love to pull all of that out of the .rb file and into some external config file. Ideally it would be as lightweight as possible. For example, just copy-paste that into another ruby file and then cram it in at runtime.
I've tried both require
and include
and gotten varying errors. Without resorting to something like YAML, what's an easy and robust way to do this?
Upvotes: 0
Views: 168
Reputation: 2267
There are a few standard ways to realize what you describe.
Each of those environmental stores a particular parameter. Then users can control, if they want to change some or all of the parameters.
An example:
key_file = ENV['KEY_FILE'] || "henrb028.key"
Then either or both of each user and the system administrator can control and change it, when needed. How to determine the filename of the configuration file varies.
A (crude!) example:
Suppose /etc/OUR_CONFIG.txt
is as follows,
CONSUMER_FILE: henrb028.consumer
KEY_FILE: henrb028.key
Then, read them like,
opts = { 'KEY_FILE' => 'default.key' }
IO.readlines("/etc/OUR_CONFIG.txt").each do |ec|
a = ec.strip.split(/\s*:\s*/)
opts[a[0]] = a[1]
end
p opts
If some (or all) options are not specified at the run time, it should fall back to the default value. OptionParser (as @tadaman suggested in his/her comment) is a powerful and versatile library to handle command-line options.
A crude example (without using OptionParser):
opts = { 'key_file' => 'default.key' }
%w(consumer_file key_file).each do |ec|
cands = ARGV.grep(/^--#{Regexp.quote ec}=.+/)
opts[ec] = cands[0].split('=')[1] unless cands.empty?
end
p opts
I think these are the most typical ways, though there are other ways!
Upvotes: 2