Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
tilo committed Jul 2, 2024
1 parent 8acbcfd commit 312b540
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
15 changes: 8 additions & 7 deletions lib/smarter_csv/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ module SmarterCSV
# headers : defaults to []

# IMPORTANT NOTES:
# 1) Data hashes could contain strings or symbols as keys.
# Make sure to use the correct form when specifying headers manually,
# in combination with the :discover_headers option
# 2)
# * Data hashes could contain strings or symbols as keys.
# Make sure to use the correct form when specifying headers manually,
# in combination with the :discover_headers option

class Writer
def initialize(file_path, options = {})
Expand Down Expand Up @@ -63,9 +62,11 @@ def finalize
private

def process_hash(hash)
hash_keys = hash.keys
new_keys = hash_keys - @headers
@headers.concat(new_keys)
if @discover_headers
hash_keys = hash.keys
new_keys = hash_keys - @headers
@headers.concat(new_keys)
end

# Reorder the hash to match the current headers order and fill missing fields
ordered_row = @headers.map { |header| hash[header] || '' }
Expand Down
15 changes: 15 additions & 0 deletions spec/smarter_csv/writer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,21 @@
expect(output).to include("Mike,35,Chicago,,IL\n")
expect(output).to include("Alex,,,USA,\n")
end

context "when discover_headers is turned off" do
let(:options) { {discover_headers: false, headers: [:name, :country]} }

it 'writes the given headers and data correctly' do
create_csv_file
output = File.read(file_path)

expect(output).to include("name,country\n")
expect(output).to include("John,\n")
expect(output).to include("Jane,USA\n")
expect(output).to include("Mike,\n")
expect(output).to include("Alex,USA\n")
end
end
end

context 'when headers are given in advance' do
Expand Down

0 comments on commit 312b540

Please sign in to comment.