Class: Csvtool::Infrastructure::Output::CsvRowFileWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/csvtool/infrastructure/output/csv_row_file_writer.rb

Instance Method Summary collapse

Constructor Details

#initialize(row_streamer:) ⇒ CsvRowFileWriter

Returns a new instance of CsvRowFileWriter.



9
10
11
# File 'lib/csvtool/infrastructure/output/csv_row_file_writer.rb', line 9

def initialize(row_streamer:)
  @row_streamer = row_streamer
end

Instance Method Details

#call(file_path:, col_sep:, headers:, start_row:, end_row:, output_path:) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/csvtool/infrastructure/output/csv_row_file_writer.rb', line 13

def call(file_path:, col_sep:, headers:, start_row:, end_row:, output_path:)
  csv = nil
  wrote_rows = false

  stats = @row_streamer.each_in_range(
    file_path: file_path,
    col_sep: col_sep,
    start_row: start_row,
    end_row: end_row
  ) do |fields|
    unless wrote_rows
      csv = ::CSV.open(output_path, "w")
      csv << headers
      wrote_rows = true
    end
    csv << fields
  end

  stats.merge(wrote_rows: wrote_rows)
ensure
  csv&.close unless csv&.closed?
end