Skip to content

Commit 3a74386

Browse files
authored
Add delimiter override option for CSVs (#865)
If you want to render values separated with, say, semicolon, this patch lets you do this: ```ruby users = User.all UserExport.new(users, delimiter: ";").call ``` Since the vast majority will use commas, I've set comma as the default keyword argument, so this will still work: ```ruby users = User.all UserExport.new(users).call ``` Also added a quickdraw test. Hope this looks okay! This is my first PR here, so if I'm missing any coding standard, let me know. :)
1 parent 2e858fb commit 3a74386

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

lib/phlex/csv.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ class Phlex::CSV
44
FORMULA_PREFIXES = Set["=", "+", "-", "@", "\t", "\r"].freeze
55
SPACE_CHARACTERS = Set[" ", "\t", "\r"].freeze
66

7-
def initialize(collection)
7+
def initialize(collection, delimiter: ",")
88
@collection = collection
9+
@delimiter = delimiter
910
@_headers = []
1011
@_current_row = []
1112
@_current_column_index = 0
@@ -44,10 +45,10 @@ def escape_csv_injection? = true
4445
view_template(*args, **kwargs)
4546

4647
if @_first && render_headers?
47-
buffer << @_headers.join(",") << "\n"
48+
buffer << @_headers.join(@delimiter) << "\n"
4849
end
4950

50-
buffer << @_current_row.join(",") << "\n"
51+
buffer << @_current_row.join(@delimiter) << "\n"
5152
@_current_column_index = 0
5253
@_current_row.clear
5354
end

quickdraw/csv.test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,19 @@ def render_headers?
4646
CSV
4747
end
4848

49+
test "basic csv with semicolon as delimiter" do
50+
products = [
51+
Product.new("Apple", 1.00),
52+
Product.new(" Banana ", 2.00),
53+
]
54+
55+
assert_equal Example.new(products, delimiter: ";").call, <<~CSV
56+
name;price
57+
Apple;1.0
58+
" Banana ";2.0
59+
CSV
60+
end
61+
4962
test "trim whitespace" do
5063
products = [
5164
Product.new(" Apple", 1.00),

0 commit comments

Comments
 (0)