Skip to content

Commit

Permalink
Merge pull request #146 from emancu/issue-143/dump_backslashed_keys
Browse files Browse the repository at this point in the history
[147] Dump backslashed keys
  • Loading branch information
emancu authored Jan 21, 2024
2 parents 3e73482 + d386129 commit bb56812
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/toml-rb/dumper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 17 additions & 0 deletions test/dumper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit bb56812

Please sign in to comment.