From: James Gray Date: 2008-01-10T03:25:40+09:00 Subject: Re: using ruby for config files On Jan 9, 2008, at 11:35 AM, furtive.clown@gmail.com wrote: > On Jan 9, 9:44 am, Karl von Laudermann > wrote: >> >> If you just want to have configuration files that are little more >> than >> key/value pairs, why not use the Windows INI file format? There are >> already ruby gems that provide read/write access to INI files: > > Because using XML, YAML, or INI files robs me of the occasional #map, > for instance, as shown in my example. The whole point is that I > *don't* want configuration files that are little more than key/value > pairs. Even if that was the case at the beginning of the project, > eventually it becomes too restrictive as the project grows. I sometimes use the stupid simple: #!/usr/bin/env ruby -wKU require "ostruct" module Config module_function def load_config_file(path) eval <<-END_CONFIG config = OpenStruct.new #{File.read(path)} config END_CONFIG end end __END__ Here are the tests: #!/usr/bin/env ruby -wKU require "test/unit" require "tempfile" require "config" class TestConfig < Test::Unit::TestCase def test_config_returns_a_customized_ostruct assert_instance_of(OpenStruct, config) end def test_config_object_is_passed_into_the_file_and_used_to_set_options c = config(<<-END_SETTINGS) config.string_setting = "just a String" config.integer_setting = 41 END_SETTINGS assert_equal("just a String", c.string_setting) assert_equal(41, c.integer_setting) end def test_exceptions_bubble_up_to_the_caller assert_raise(RuntimeError) do config(<<-END_ERROR) raise "Oops!" END_ERROR end end private def config(content = String.new) cf = Tempfile.new("ender_config_test") cf << content cf.flush Config.load_config_file(cf.path) end end __END__ James Edward Gray II