Class: Fech::CsvDoctor

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

Class Method Summary collapse

Methods inherited from Csv

clean_opts

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.

Parameters:

  • opts (Hash)

    a customizable set of options

Options Hash (opts):

  • :row_type (Boolean)

    yield only rows that match this type



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/fech/csv.rb', line 41

def self.parse_row(file_path, opts)
  File.open(file_path, "r:#{opts[:encoding]}").each do |line|
    # Skip empty lines
    next if line.strip.empty?

    # Skip non-matching row-types
    next if opts.key?(:row_type) && !Fech.regexify(opts[:row_type]).match(line)

    yield safe_line(line, clean_opts(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



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

def self.safe_line(line, opts)
  # :encoding isn't a valid argument to Csv#parse_line
  opts.delete(:encoding)
  begin
    parse_line(line, opts)
  rescue Fech::Csv::MalformedCSVError
    row = parse_line(line, clean_opts(opts).merge(:quote_char => "\0"))
    row.map! { |val| safe_value(val) }
  end
end

.safe_value(val) ⇒ Object

Removes extraneous quotes from values.



69
70
71
72
73
74
75
76
# File 'lib/fech/csv.rb', line 69

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