Module: CsvParser

Defined in:
lib/csv_parser.rb,
lib/csv_parser/result.rb,
lib/csv_parser/version.rb,
lib/csv_parser/csv_parser.rb,
lib/csv_parser/parser_extensions.rb

Defined Under Namespace

Modules: Csv, ParserExtensions Classes: CsvParser, Error, ExtraFieldsError, MissingFieldsError, MissingQuoteError, Result, StrayQuoteError

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.error(type, line, column, msg = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/csv_parser.rb', line 43

def self.error(type, line, column, msg = nil)
  klass, msg =
    case type
    when :missing_quote
      [MissingQuoteError, "no ending quote found for quote on line #{line}, column #{column}"]
    when :stray_quote
      [StrayQuoteError, "invalid quote found on line #{line}, column #{column}"]
    when :missing_fields
      [MissingFieldsError, "record on line #{line} had too few fields"]
    when :extra_fields
      [ExtraFieldsError, "record on line #{line} had too many fields"]
    else
      Error
    end

  klass.new(msg, line, column)
end

.parse(data, options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/csv_parser.rb', line 26

def self.parse(data, options = {})
  parser = ::CsvParser::CsvParser.new
  options.each_pair do |key, value|
    parser.send("#{key}=", value)
  end
  result = parser.parse(data)
  if result
    warnings = parser.warnings.collect do |(desc, line, col)|
      error(desc, line, col)
    end
    Result.new(result.value, warnings)
  else
    raise error(parser.failure_type, parser.failure_line,
                parser.failure_column, parser.failure_reason)
  end
end