Class: Fech::CsvDoctor

Inherits:
Csv
  • Object
show all
Defined in:
lib/fech/csv.rb

Class Method Summary collapse

Class Method Details

.parse_row(file_path, opts) ⇒ Object

Skips FasterCSV’s whole-file wrapper, and passes each line in the file to a function that will parse it individually.



36
37
38
39
40
41
42
43
44
# File 'lib/fech/csv.rb', line 36

def self.parse_row(file_path, opts)
  opts.reject! {|k,v| ![:col_sep, :quote_char].include?(k)}

  File.open(file_path, 'r').each do |line|
    # Skip empty lines
    next if line.strip.empty?
    yield safe_line(line, opts)
  end
end

.safe_line(line, opts) ⇒ Object

Tries to parse the line with FasterCSV.parse_line and the given quote_char. If this fails, try again with the “0” quote_char.

Parameters:

  • line (String)

    the file’s row to parse



50
51
52
53
54
55
56
57
# File 'lib/fech/csv.rb', line 50

def self.safe_line(line, opts)
  begin
    parse_line(line, opts)
  rescue Fech::Csv::MalformedCSVError
    row = parse_line(line, opts.merge(:quote_char => "\0"))
    row.map! { |val| safe_value(val) }
  end
end

.safe_value(val) ⇒ Object

Removes extraneous quotes from values.



60
61
62
63
64
65
66
67
# File 'lib/fech/csv.rb', line 60

def self.safe_value(val)
  return val unless val.is_a?(String)
  begin
    parse_line(val).first
  rescue Fech::Csv::MalformedCSVError
    val
  end
end