lib/io_streams/tabular/utility/csv_row.rb in iostreams-0.20.3 vs lib/io_streams/tabular/utility/csv_row.rb in iostreams-1.0.0.beta

- old
+ new

@@ -22,47 +22,49 @@ # Parameters # line [String] # A single line of CSV data without any line terminators def parse(line) return if IOStreams::Utils.blank?(line) - return if @skip_lines and @skip_lines.match line + return if @skip_lines&.match(line) in_extended_col = false - csv = Array.new + csv = [] parts = line.split(@col_sep, -1) csv << nil if parts.empty? # This loop is the hot path of csv parsing. Some things may be non-dry # for a reason. Make sure to benchmark when refactoring. parts.each do |part| if in_extended_col # If we are continuing a previous column - if part[-1] == @quote_char && part.count(@quote_char) % 2 != 0 + if part[-1] == @quote_char && part.count(@quote_char).odd? # extended column ends csv.last << part[0..-2] if csv.last =~ @parsers[:stray_quote] raise MalformedCSVError, "Missing or stray quote in line #{lineno + 1}" end + csv.last.gsub!(@quote_char * 2, @quote_char) in_extended_col = false else csv.last << part csv.last << @col_sep end elsif part[0] == @quote_char # If we are starting a new quoted column - if part[-1] != @quote_char || part.count(@quote_char) % 2 != 0 + if part[-1] != @quote_char || part.count(@quote_char).odd? # start an extended column csv << part[1..-1] csv.last << @col_sep in_extended_col = true else # regular quoted column csv << part[1..-2] if csv.last =~ @parsers[:stray_quote] raise MalformedCSVError, "Missing or stray quote in line #{lineno + 1}" end + csv.last.gsub!(@quote_char * 2, @quote_char) end elsif part =~ @parsers[:quote_or_nl] # Unquoted field with bad characters. if part =~ @parsers[:nl_or_lf] @@ -88,16 +90,16 @@ # save fields unconverted fields, if needed... unconverted = csv.dup if @unconverted_fields # convert fields, if needed... - csv = convert_fields(csv) unless @use_headers or @converters.empty? + csv = convert_fields(csv) unless @use_headers || @converters.empty? # parse out header rows and handle CSV::Row conversions... csv = parse_headers(csv) if @use_headers # inject unconverted fields and accessor, if requested... - if @unconverted_fields and not csv.respond_to? :unconverted_fields + if @unconverted_fields && (!csv.respond_to? :unconverted_fields) add_unconverted_fields(csv, unconverted) end csv end @@ -105,11 +107,10 @@ # Return the supplied array as a single line CSV string. def render(row) row.map(&@quote).join(@col_sep) + @row_sep # quote and separate end - alias_method :to_csv, :render - + alias to_csv render end end end end