Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[147] Dump backslashed keys #146

Merged
merged 2 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading