diff --git a/lib/toml-rb/dumper.rb b/lib/toml-rb/dumper.rb index fca16c4..628d8d5 100644 --- a/lib/toml-rb/dumper.rb +++ b/lib/toml-rb/dumper.rb @@ -108,8 +108,13 @@ def bare_key?(key) !!key.to_s.match(/^[a-zA-Z0-9_-]*$/) end + # The key needs to use quotes according to TOML specs. + # Ruby representation of literals or strings, mixed with special characters + # made the concatenation error-prone, luckiley the `#inspect` method returns + # exactly what we need. I decided to keep the method `quote_key/1` + # for readability. def quote_key(key) - '"' + key.gsub('"', '\\"') + '"' + key.inspect end end end diff --git a/test/dumper_test.rb b/test/dumper_test.rb index ff4f9ef..c6e2668 100644 --- a/test/dumper_test.rb +++ b/test/dumper_test.rb @@ -108,18 +108,35 @@ def test_dump_array_tables def test_dump_interpolation_curly hash = {"key" => "includes \#{variable}"} dumped = TomlRB.dump(hash) + assert_equal %(key = "includes \#{variable}") + "\n", dumped end def test_dump_interpolation_at hash = {"key" => 'includes #@variable'} dumped = TomlRB.dump(hash) + assert_equal 'key = "includes #@variable"' + "\n", dumped end def test_dump_interpolation_dollar hash = {"key" => 'includes #$variable'} dumped = TomlRB.dump(hash) + assert_equal 'key = "includes #$variable"' + "\n", dumped end + + def test_dump_special_chars_in_literals + hash = {'\t' => "escape special chars in string literals"} + dumped = TomlRB.dump(hash) + + assert_equal %("\\\\t" = "escape special chars in string literals") + "\n", dumped + end + + def test_dump_special_chars_in_strings + hash = {"\t" => "escape special chars in strings"} + dumped = TomlRB.dump(hash) + + assert_equal %("\\t" = "escape special chars in strings") + "\n", dumped + end end