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 bd77cb5 commit 813c1f4
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/smarter_csv/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ def initialize(file_path, options = {})
@options = options
@discover_headers = options.has_key?(:discover_headers) ? (options[:discover_headers] == true) : true
@headers = options[:headers] || []
@row_sep = options[:row_sep] || "\n" # RFC4180 "\r\n"
@col_sep = options[:col_sep] || ','
@quote_char = '"'
@force_quotes = options[:force_quotes]
@map_headers = options[:map_headers] || {}
@temp_file = Tempfile.new('tempfile', '/tmp')
@output_file = File.open(file_path, 'w+')
@quote_regex = Regexp.union(@col_sep, @row_sep, @quote_char)
end

def append(array_of_hashes)
Expand All @@ -30,7 +33,7 @@ def append(array_of_hashes)
# Reorder the hash to match the current headers order and fill missing fields
ordered_row = @headers.map { |header| hash[header] || '' }

@temp_file.puts ordered_row.map { |value| escape_csv_field(value) }.join(@col_sep)
@temp_file.write ordered_row.map { |value| escape_csv_field(value) }.join(@col_sep) + @row_sep
end
end

Expand All @@ -39,17 +42,16 @@ def finalize
mapped_headers = @headers.map { |header| @map_headers[header] || header }

@temp_file.rewind
@output_file.write(mapped_headers.join(@col_sep) + "\n")
@output_file.write(mapped_headers.join(@col_sep) + @row_sep)
@output_file.write(@temp_file.read)
@output_file.flush
@output_file.close
end

private

SPECIAL_CHARS = /[,\"\n]/
def escape_csv_field(field)
if @force_quotes || field.to_s.match(SPECIAL_CHARS)
if @force_quotes || field.to_s.match(@quote_regex)
"\"#{field}\""
else
field.to_s
Expand Down

0 comments on commit 813c1f4

Please sign in to comment.