Class: Etna::CsvExporter

Inherits:
Object
  • Object
show all
Defined in:
lib/etna/csvs.rb

Defined Under Namespace

Classes: RowWriteable

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column_headers, &column_serializer) ⇒ CsvExporter

Returns a new instance of CsvExporter.



108
109
110
111
# File 'lib/etna/csvs.rb', line 108

def initialize(column_headers, &column_serializer)
  @column_headers = column_headers
  @column_serializer = column_serializer
end

Instance Attribute Details

#column_headersObject (readonly)

column_headers should be an array of symbols, mapping the column heading names and ordering to export column_serializer is an optional block that takes column (string), column_value (string) and should

return a string representation of column_value to write to the csv.  By default, when nil, the exporter
will attempt to convert the value to a string via to_s or simply write an empty string for nil.


107
108
109
# File 'lib/etna/csvs.rb', line 107

def column_headers
  @column_headers
end

Instance Method Details

#header_rowObject



113
114
115
# File 'lib/etna/csvs.rb', line 113

def header_row
  @column_headers.map(&:to_s)
end

#map_column_value(column, column_value) ⇒ Object



117
118
119
# File 'lib/etna/csvs.rb', line 117

def map_column_value(column, column_value)
  @column_serializer&.call(column, column_value) || column_value&.to_s || ''
end

#row_from_columns(columns) ⇒ Object



121
122
123
# File 'lib/etna/csvs.rb', line 121

def row_from_columns(columns)
  @column_headers.map { |c| self.map_column_value(c, columns[c] || '') }
end

#with_row_writeable(filename: nil, output_io: nil) {|writeable| ... } ⇒ Object

Yields:

  • (writeable)


125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/etna/csvs.rb', line 125

def with_row_writeable(filename: nil, output_io: nil, &block)
  if output_io.nil? && !filename.nil?
    File.open(filename, 'w') do |io|
      return with_row_writeable(output_io: io, &block)
    end
  end

  writeable = self.class::RowWriteable.new(self, CSV.new(output_io))
  yield writeable
  writeable.ensure_headers
  nil
end