From 5883615ebfa0a603c2fd8437a9a678058692a6dd Mon Sep 17 00:00:00 2001 From: Emiliano Mancuso Date: Sun, 7 Jan 2024 10:13:24 -0300 Subject: [PATCH 1/2] [147] Dump backslashed keys --- test/dumper_test.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/dumper_test.rb b/test/dumper_test.rb index ff4f9ef..e936bd2 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 From d3861291a10b7266a4bd6c42f06207ed636304ff Mon Sep 17 00:00:00 2001 From: Emiliano Mancuso Date: Sun, 21 Jan 2024 12:39:08 +0000 Subject: [PATCH 2/2] Fix error --- lib/toml-rb/dumper.rb | 7 ++++++- test/dumper_test.rb | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) 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 e936bd2..c6e2668 100644 --- a/test/dumper_test.rb +++ b/test/dumper_test.rb @@ -130,13 +130,13 @@ 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 + 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 + assert_equal %("\\t" = "escape special chars in strings") + "\n", dumped end end