dot method alteration similar to git, prevents alteration of non leaf settings

This commit is contained in:
John Bender 2010-01-24 00:09:15 -08:00
parent 2883130434
commit bb3496c6a6
3 changed files with 29 additions and 3 deletions

View File

@ -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

View File

@ -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

View File

@ -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