Skip to content

Commit

Permalink
fix issue 294 with writing headers with quotes (#295)
Browse files Browse the repository at this point in the history
  • Loading branch information
tilo authored Dec 12, 2024
1 parent 39dceb6 commit 2932041
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@

# SmarterCSV 1.x Change Log

## 1.13.1 (2024-12-12)
* fix bug with SmarterCSV.generate with `force_quotes: true` ([issue 294](https://github.com/tilo/smarter_csv/issues/294))

## 1.13.0 (2024-11-06) ⚡ POTENTIALLY BREAKING ⚡

CHANGED DEFAULT BEHAVIOR
Expand Down
2 changes: 1 addition & 1 deletion lib/smarter_csv/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module SmarterCSV
VERSION = "1.13.0"
VERSION = "1.13.1"
end
1 change: 1 addition & 0 deletions lib/smarter_csv/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def <<(data)
def finalize
# Map headers if :map_headers option is provided
mapped_headers = @headers.map { |header| @map_headers[header] || header }
mapped_headers = mapped_headers.map{|x| escape_csv_field(x)} if @force_quotes

@temp_file.rewind
@output_file.write(mapped_headers.join(@col_sep) + @row_sep)
Expand Down
19 changes: 18 additions & 1 deletion spec/smarter_csv/writer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,24 @@
writer << [{ a: 'hello', b: 'world' }]
writer.finalize

expect(File.read(file_path)).to eq("a,b#{row_sep}\"hello\",\"world\"#{row_sep}")
expect(File.read(file_path)).to eq("\"a\",\"b\"#{row_sep}\"hello\",\"world\"#{row_sep}")
end

context 'force_quotes also applies to headers' do
let(:options) { {force_quotes: true} }
let(:data) do
{ name: 'John', age: 30, city: 'New York' }
end

it 'writes the given headers and data correctly' do
writer = SmarterCSV::Writer.new(file_path, options)
writer << data
writer.finalize
output = File.read(file_path)

expect(output).to include("\"name\",\"age\",\"city\"#{row_sep}")
expect(output).to include("\"John\",\"30\",\"New York\"#{row_sep}")
end
end
end

Expand Down

0 comments on commit 2932041

Please sign in to comment.