From 3a743862b5e6bed78ac1c02c1c8ebc35d7840abb Mon Sep 17 00:00:00 2001 From: Even Fangberget Onsager Date: Tue, 18 Feb 2025 14:31:05 +0100 Subject: [PATCH] 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. :) --- lib/phlex/csv.rb | 7 ++++--- quickdraw/csv.test.rb | 13 +++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/phlex/csv.rb b/lib/phlex/csv.rb index 14419ca2..589df0f3 100644 --- a/lib/phlex/csv.rb +++ b/lib/phlex/csv.rb @@ -4,8 +4,9 @@ class Phlex::CSV FORMULA_PREFIXES = Set["=", "+", "-", "@", "\t", "\r"].freeze SPACE_CHARACTERS = Set[" ", "\t", "\r"].freeze - def initialize(collection) + def initialize(collection, delimiter: ",") @collection = collection + @delimiter = delimiter @_headers = [] @_current_row = [] @_current_column_index = 0 @@ -44,10 +45,10 @@ def escape_csv_injection? = true view_template(*args, **kwargs) if @_first && render_headers? - buffer << @_headers.join(",") << "\n" + buffer << @_headers.join(@delimiter) << "\n" end - buffer << @_current_row.join(",") << "\n" + buffer << @_current_row.join(@delimiter) << "\n" @_current_column_index = 0 @_current_row.clear end diff --git a/quickdraw/csv.test.rb b/quickdraw/csv.test.rb index 5c9ddb36..f243821d 100644 --- a/quickdraw/csv.test.rb +++ b/quickdraw/csv.test.rb @@ -46,6 +46,19 @@ def render_headers? CSV end +test "basic csv with semicolon as delimiter" do + products = [ + Product.new("Apple", 1.00), + Product.new(" Banana ", 2.00), + ] + + assert_equal Example.new(products, delimiter: ";").call, <<~CSV + name;price + Apple;1.0 + " Banana ";2.0 + CSV +end + test "trim whitespace" do products = [ Product.new(" Apple", 1.00),