Ruby Configuration File Parser
drks — Tue, 2006-11-21 07:56
After a bit of Googling around, I was unable to find a simple config file parser that did what I wanted it to do. Therefore, I have written such a class, and it is available should anyone else find it useful.
Get ParseConfig now.
The usage is quite simple. Say you have a configuration file similar to the following:
server_id = web01 server_ip_address = 192.168.1.102 ...
Should you be wanting to parse that configuration into a Ruby application, you can simply do the following:
require ('parseconfig') my_config = ParseConfig.new('/path/to/config/file.conf') puts my_config.get_value('server_id')
As you would guess, the output of the script above would be 'web01' (the value of the server_id param). Could it be any simpler??? I hope you enjoy... please send any comments or suggestions my way.
Thanks!
Update: ParseConfig is now available (or has been for a long time) via ruby gems:
you@linuxbox ~]$ sudo gem install parseconfig
Then:
require ('rubygems') require ('parseconfig') my_config = ParseConfig.new('/path/to/config/file.conf') puts my_config.get_value('server_id')
There are also some improvements. As of 0.4.3, you can simply access the params hash:
require ('rubygems') require ('parseconfig') my_config = ParseConfig.new('/path/to/config/file.conf') puts my_config['server_id']
As well as get a listing of all available params:
my_config.get_params()
Returns an array of all the params available in the config file.
As of 0.5, you can now read config files with [groups] such as MySQL's my.cnf:
#!/usr/bin/ruby require('rubygems') require('parseconfig') c = ParseConfig.new('./my.cnf') puts puts "Available config groups: #{c.groups}" puts puts "config['client']['user'] => #{c.params['client']['user']}" puts "config['client']['password'] => #{c.params['client']['password']}" puts
And the output:
you@linuxbox ~] $ cat ./my.cnf [client] user=johnny password=3uS1F1eufy75 you@linuxbox ~] $ ruby ./read_my_cnf.rb Available config groups: client config['client']['user'] => johnny config['client']['password'] => 3uS1F1eufy75
RSS Feed