class IOStreams::Tabular::Parser::Csv

Attributes

csv_parser[R]

Public Class Methods

new() click to toggle source
# File lib/io_streams/tabular/parser/csv.rb, line 9
def initialize
  @csv_parser = Utility::CSVRow.new
end

Public Instance Methods

parse(row) click to toggle source

Returns [Array] the parsed CSV line

# File lib/io_streams/tabular/parser/csv.rb, line 27
def parse(row)
  return row if row.is_a?(::Array)

  raise(IOStreams::Errors::TypeMismatch, "Format is :csv. Invalid input: #{row.class.name}") unless row.is_a?(String)

  parse_line(row)
end
parse_header(row) click to toggle source

Returns [Array<String>] the header row. Returns nil if the row is blank.

# File lib/io_streams/tabular/parser/csv.rb, line 16
def parse_header(row)
  return row if row.is_a?(::Array)

  unless row.is_a?(String)
    raise(IOStreams::Errors::InvalidHeader, "Format is :csv. Invalid input header: #{row.class.name}")
  end

  parse_line(row)
end
render(row, header) click to toggle source

Return the supplied array as a single line CSV string.

# File lib/io_streams/tabular/parser/csv.rb, line 36
def render(row, header)
  array = header.to_array(row)
  render_array(array)
end

Private Instance Methods

parse_line(line) click to toggle source

About 10 times slower than the approach used in Ruby 2.5 and earlier, but at least it works on Ruby 2.6 and above.

# File lib/io_streams/tabular/parser/csv.rb, line 46
def parse_line(line)
  return if IOStreams::Utils.blank?(line)

  CSV.parse_line(line)
end
render_array(array) click to toggle source
# File lib/io_streams/tabular/parser/csv.rb, line 52
def render_array(array)
  CSV.generate_line(array, encoding: "UTF-8", row_sep: "")
end