Skip to content

Commit

Permalink
Add delimiter override option for CSVs (#865)
Browse files Browse the repository at this point in the history
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. :)
  • Loading branch information
evenreven authored Feb 18, 2025
1 parent 2e858fb commit 3a74386
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/phlex/csv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions quickdraw/csv.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 3a74386

Please sign in to comment.