Ruby ParseConfig Demo
drks — Mon, 2009-09-21 17:45
Example Config File
admin_email = root@localhost listen_ip = 127.0.0.1 listen_port = 87345 [group1] user_name = johnny group_name = daemons [group2] user_name = rita group_name = daemons
Example Ruby Code to Use ParseConfig
#!/usr/bin/env ruby require('rubygems') require('parseconfig') #require('./lib/parseconfig.rb') begin c = ParseConfig.new('demo.conf') rescue Errno::ENOENT puts "The config file you specified was not found" exit rescue Errno::EACCES puts "The config file you specified is not readable" exit end puts puts 'Reading main config section and groups...' puts '-' * 77 puts c.write() puts puts 'Available params are...' puts '-' * 77 puts puts c.get_params() puts puts puts 'Available sub-groups are...' puts '-' * 77 puts puts c.get_groups() puts puts puts 'Accessing sub-group params...' puts '-' * 77 puts puts "group1 user name value is: #{c.params['group1']['user_name']}" puts puts puts "Using params hash..." puts '-' * 77 puts puts "The admin email address is #{c.params['admin_email']}" puts puts puts "Using get_value (kind of deprecated)..." puts '-' * 77 puts puts "The listen address is #{c.get_value('listen_ip')} and the user name " + "is #{c.get_value('group1')['user_name']}" puts puts puts "Writing the config out to a file" puts '-' * 77 puts f = open('/tmp/parseconfig_sample_config', 'w') c.write(f) f.close() puts "Config written to /tmp/parseconfig_sample_config" puts
And The Output
wdierkes@macbook-pro [trunk] $ ruby demo.rb Reading main config section and groups... ----------------------------------------------------------------------------- listen_port = 87345 admin_email = "root@localhost" listen_ip = "127.0.0.1" [group1] group_name = daemons user_name = johnny [group2] group_name = daemons user_name = rita Available params are... ----------------------------------------------------------------------------- listen_port admin_email group1 listen_ip group2 Available sub-groups are... ----------------------------------------------------------------------------- group1 group2 Accessing sub-group params... ----------------------------------------------------------------------------- group1 user name value is: johnny Using params hash... ----------------------------------------------------------------------------- The admin email address is root@localhost Using get_value (kind of deprecated)... ----------------------------------------------------------------------------- The listen address is 127.0.0.1 and the user name is johnny Writing the config out to a file ----------------------------------------------------------------------------- Config written to /tmp/parseconfig_sample_config
RSS Feed
Post new comment