Sha256: e174f0c0be6a4bb355823d1e8751bbb486e51ffae6d4ee564e52d1855af1a8b0

Contents?: true

Size: 1.7 KB

Versions: 9

Compression:

Stored size: 1.7 KB

Contents

require 'csv'
module IOStreams
  class Tabular
    module Parser
      class Csv < Base
        attr_reader :csv_parser

        def initialize
          @csv_parser = Utility::CSVRow.new unless RUBY_VERSION.to_f >= 2.6
        end

        # Returns [Array<String>] the header row.
        # Returns nil if the row is blank.
        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

        # Returns [Array] the parsed CSV line
        def parse(row)
          return row if row.is_a?(::Array)

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

          parse_line(row)
        end

        # Return the supplied array as a single line CSV string.
        def render(row, header)
          array = header.to_array(row)
          render_array(array)
        end

        private

        if RUBY_VERSION.to_f >= 2.6
          # 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.
          def parse_line(line)
            return if IOStreams::Utils.blank?(line)

            CSV.parse_line(line)
          end

          def render_array(array)
            CSV.generate_line(array, encoding: 'UTF-8', row_sep: '')
          end
        else
          def parse_line(line)
            csv_parser.parse(line)
          end

          def render_array(array)
            csv_parser.to_csv(array)
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
iostreams-1.1.0 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta7 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta6 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta5 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta4 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta3 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta2 lib/io_streams/tabular/parser/csv.rb
iostreams-1.0.0.beta lib/io_streams/tabular/parser/csv.rb