Skip to content

Commit cff8b18

Browse files
authored
Add undef: :replace for CSV.open (#129)
This PR adds `undef: :replace` option for `CSV.open`. `File.open` has `undef: :replace` option, but `CSV.open` does not. It would be convenient if `CSV.open` could have a shortcut by having `undef: :replace` option.
1 parent 8c26c0a commit cff8b18

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/csv.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -960,6 +960,11 @@ def generate_line(row, **options)
960960
# open( filename, mode = "rb", **options )
961961
# open( filename, **options )
962962
#
963+
# possible options elements:
964+
# hash form:
965+
# :undef => :replace # replace undefined conversion
966+
# :replace => string # replacement string ("?" or "\uFFFD" if not specified)
967+
#
963968
# This method opens an IO object, and wraps that with CSV. This is intended
964969
# as the primary interface for writing a CSV file.
965970
#
@@ -1021,6 +1026,8 @@ def open(filename, mode="r", **options)
10211026
# wrap a File opened with the remaining +args+ with no newline
10221027
# decorator
10231028
file_opts = {universal_newline: false}.merge(options)
1029+
options.delete(:undef)
1030+
options.delete(:replace)
10241031

10251032
begin
10261033
f = File.open(filename, mode, **file_opts)

test/csv/interface/test_read.rb

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

128+
def test_open_with_undef_replace
129+
# U+00B7 Middle Dot
130+
CSV.open(@input.path, "w", encoding: Encoding::CP932, undef: :replace) do |rows|
131+
rows << ["\u00B7"]
132+
end
133+
CSV.open(@input.path, encoding: Encoding::CP932) do |csv|
134+
assert_equal([["?"]],
135+
csv.to_a)
136+
end
137+
end
138+
139+
def test_open_with_undef_replace_and_replace_string
140+
# U+00B7 Middle Dot
141+
CSV.open(@input.path, "w", encoding: Encoding::CP932, undef: :replace, replace: "X") do |rows|
142+
rows << ["\u00B7"]
143+
end
144+
CSV.open(@input.path, encoding: Encoding::CP932) do |csv|
145+
assert_equal([["X"]],
146+
csv.to_a)
147+
end
148+
end
149+
128150
def test_parse
129151
assert_equal(@rows,
130152
CSV.parse(@data, col_sep: "\t", row_sep: "\r\n"))

0 commit comments

Comments
 (0)