diff --git a/lib/hobo/config.rb b/lib/hobo/config.rb index 26cfcb010..7b16d6439 100644 --- a/lib/hobo/config.rb +++ b/lib/hobo/config.rb @@ -1,4 +1,6 @@ module Hobo + + module_function def config @@ -9,8 +11,21 @@ module Hobo @@alterable_config end - def set_config!(hash) + def config!(hash) @@alterable_config = hash.dup @@config = hash.freeze end + + def set_config_value(chain, val, cfg=@@alterable_config) + keys = chain.split('.') + key = keys.shift.to_sym + if keys.empty? + raise InvalidSettingAlteration if cfg[key].instance_of?(Hash) + return cfg[key] = val if keys.empty? + end + + set_config_value(keys.join('.'), val, cfg[key]) + end + + class InvalidSettingAlteration < StandardError; end end diff --git a/lib/hobo/env.rb b/lib/hobo/env.rb index 41b9bc3f5..7489c95ce 100644 --- a/lib/hobo/env.rb +++ b/lib/hobo/env.rb @@ -23,7 +23,7 @@ module Hobo ensure_directories ensure_files parsed = yield(CONFIG.keys.first) - Hobo.set_config!(parsed) + Hobo.config!(parsed) end end end diff --git a/test/hobo/config_test.rb b/test/hobo/config_test.rb index 7009c1167..c866ca741 100644 --- a/test/hobo/config_test.rb +++ b/test/hobo/config_test.rb @@ -5,7 +5,7 @@ class ConfigTest < Test::Unit::TestCase context "Hobo configuration" do setup do @settings = {:a => { :b => 1}} - Hobo.set_config!(@settings) + Hobo.config!(@settings) end should "prevent alteration after initial creation" do @@ -28,5 +28,16 @@ class ConfigTest < Test::Unit::TestCase Hobo.alterable_config[:a] = 1 assert_not_equal Hobo.alterable_config, Hobo.config end + + should "alter the config given a dot chain of keys" do + Hobo.set_config_value 'a.b', 2 + assert_equal Hobo.alterable_config[:a][:b], 2 + end + + should "prevent the alteration of a non leaf setting value" do + assert_raise Hobo::InvalidSettingAlteration do + Hobo.set_config_value('a', 2) + end + end end end