Skip to content
Open
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
15 changes: 14 additions & 1 deletion lib/csv/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,19 @@ def quote_field(field)
encoded_quote_character
end

# An invalid byte makes Regexp#match? raise, and the old guard then
# wrote the field raw. Search for the separator bytes instead so a
# newline or comma still forces quotes (csv#395).
def field_needs_quotes?(field)
return @quotable_pattern.match?(field) if field.valid_encoding?

encoding = field.encoding
field.include?("\r".encode(encoding)) ||
field.include?("\n".encode(encoding)) ||
field.include?(@column_separator.encode(encoding)) ||
field.include?(@quote_character.encode(encoding))
end

def quote(field, i)
if @force_quotes
quote_field(field)
Expand All @@ -197,7 +210,7 @@ def quote(field, i)
else
field = String(field) # Stringify fields
# represent empty fields as empty quoted fields
if (@quote_empty and field.empty?) or (field.valid_encoding? and @quotable_pattern.match?(field))
if (@quote_empty and field.empty?) or field_needs_quotes?(field)
quote_field(field)
else
field # unquoted field
Expand Down
24 changes: 24 additions & 0 deletions test/csv/write/test_general.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,30 @@ def test_quote
generate_line(["foo", %Q["bar"], "baz"]))
end

def test_quote_invalid_encoding
["UTF-8", "Shift_JIS", "EUC-JP"].each do |name|
newline = "x\xFF\nadmin,true".dup.force_encoding(name)
assert_equal(%Q["x\xFF\nadmin,true"#{$INPUT_RECORD_SEPARATOR}].b,
generate_line([newline]).b,
name)
comma = "x\xFF,approved".dup.force_encoding(name)
assert_equal(%Q["x\xFF,approved"#{$INPUT_RECORD_SEPARATOR}].b,
generate_line([comma]).b,
name)
quote = "x\xFF\"y".dup.force_encoding(name)
assert_equal(%Q["x\xFF""y"#{$INPUT_RECORD_SEPARATOR}].b,
generate_line([quote]).b,
name)
line = generate_line(["user", newline, "role"])
assert_equal([["user", newline.b, "role"]],
CSV.parse(line.b, encoding: "ASCII-8BIT"),
name)
end
plain = "x\xFFok".dup.force_encoding("UTF-8")
assert_equal("x\xFFok#{$INPUT_RECORD_SEPARATOR}",
generate_line([plain]))
end

def test_quote_lf
assert_equal(%Q["""\n","""\n"#{$INPUT_RECORD_SEPARATOR}],
generate_line([%Q["\n], %Q["\n]]))
Expand Down