diff --git a/lib/inifile.rb b/lib/inifile.rb index fbcfb0e..202eba6 100644 --- a/lib/inifile.rb +++ b/lib/inifile.rb @@ -133,7 +133,10 @@ def read( opts = {} ) # Returns this IniFile converted to a String. def to_s s = [] - @ini.each do |section,hash| + hash = @ini.dup + default = hash.delete(@default) + default.each {|param,val| s << "#{param} #{@param} #{escape_value val}"} + hash.each do |section,hash| s << "[#{section}]" hash.each {|param,val| s << "#{param} #{@param} #{escape_value val}"} s << "" @@ -188,14 +191,16 @@ def merge!( other ) end (other_keys - my_keys).each do |key| - @ini[key] = case other[key] - when Hash - other[key].dup - when nil - {} - else - raise Error, "cannot merge section #{key.inspect} - unsupported type: #{other[key].class.name}" - end + case other[key] + when Hash + @ini[key] = other[key].dup + when nil + @ini[key] = {} + when String + @ini[@default].merge!({key => other[key]}) + else + raise Error, "cannot merge section #{key.inspect} - unsupported type: #{other[key].class.name}" + end end self diff --git a/test/test_inifile.rb b/test/test_inifile.rb index 2026065..9d4f7d6 100644 --- a/test/test_inifile.rb +++ b/test/test_inifile.rb @@ -272,6 +272,7 @@ def test_initialize_from_string def test_initialize_from_hash hash = { + 'value' => 'bat', 'section one' => { 'foo' => 'bar', 'baz' => 'buz' @@ -296,9 +297,25 @@ def test_initialize_from_hash assert_equal '7e6ff3', ini_file['colors']['perrywinkle'] assert_equal '4682b4', ini_file['colors']['steelblue'] + assert_equal 'bat', ini_file['global']['value'] + assert_empty ini_file['empty'] end + def test_to_s + hash = { + 'one' => 'bar', + 'two' => 'bat', + 'section one' => { + 'foo' => 'baz', + } + } + + ini_file = IniFile.new(:content => hash) + + assert_equal "one = bar\ntwo = bat\n[section one]\nfoo = baz\n", ini_file.to_s + end + def test_sections expected = [ 'section_one', 'section_two', 'section three', @@ -460,9 +477,6 @@ def test_merge_invalid_hash bad_hash = { 'section_one' => [1, 2, 3, 4] } assert_raise(IniFile::Error) { @ini_file.merge(bad_hash) } - bad_hash = { 'foo' => 'bar' } - assert_raise(IniFile::Error) { @ini_file.merge(bad_hash) } - not_a_hash = [['section_one', ['foo','bar'], ['baz', 'buz']]] assert_raise(IniFile::Error) { @ini_file.merge(not_a_hash) }