Skip to content

Commit a4b528c

Browse files
authored
Fix an error for CSV.open (#131)
Follow up to https://github.com/ruby/csv/pull/130/files#r434885191. This PR fixes `ArgumentError` for `CSV.open` when processing invalid byte sequence in UTF-8.
1 parent cff8b18 commit a4b528c

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

lib/csv/writer.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def quote(field)
156156
else
157157
field = String(field) # Stringify fields
158158
# represent empty fields as empty quoted fields
159-
if (@quote_empty and field.empty?) or @quotable_pattern.match?(field)
159+
if (@quote_empty and field.empty?) or (field.valid_encoding? and @quotable_pattern.match?(field))
160160
quote_field(field)
161161
else
162162
field # unquoted field

test/csv/interface/test_read.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,16 @@ def test_open_encoding_utf_8_with_bom
125125
end
126126
end
127127

128+
def test_open_invalid_byte_sequence_in_utf_8
129+
CSV.open(@input.path, "w", encoding: Encoding::CP932) do |rows|
130+
error = assert_raise(Encoding::InvalidByteSequenceError) do
131+
rows << ["\x82\xa0"]
132+
end
133+
assert_equal('"\x82" on UTF-8',
134+
error.message)
135+
end
136+
end
137+
128138
def test_open_with_undef_replace
129139
# U+00B7 Middle Dot
130140
CSV.open(@input.path, "w", encoding: Encoding::CP932, undef: :replace) do |rows|

0 commit comments

Comments
 (0)