Module: Equalshares::Pabulib::Csv

Defined in:
lib/equalshares/pabulib/csv.rb

Overview

Low-level lexing shared by the parser: the ';'-delimited, double-quote-escaped field splitter (port of parseCSVLine in js/pabulibParser.js) and the JS-style numeric check.

Class Method Summary collapse

Class Method Details

.numeric_string?(value) ⇒ Boolean

Whether a string parses as a number the way JavaScript's Number() does: empty or whitespace-only strings count as numeric (they coerce to 0), nil does not.

Returns:

  • (Boolean)


43
44
45
46
47
48
49
50
51
52
53
# File 'lib/equalshares/pabulib/csv.rb', line 43

def numeric_string?(value)
  return false if value.nil?

  str = value.strip
  return true if str.empty?

  Float(str)
  true
rescue ArgumentError, TypeError
  false
end

.parse_line(line) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/equalshares/pabulib/csv.rb', line 11

def parse_line(line)
  result = []
  current = +""
  in_quotes = false
  i = 0

  while i < line.length
    char = line[i]
    if char == '"'
      if in_quotes && i + 1 < line.length && line[i + 1] == '"'
        current << '"'
        i += 2
      else
        in_quotes = !in_quotes
        i += 1
      end
    elsif char == ";" && !in_quotes
      result << current
      current = +""
      i += 1
    else
      current << char
      i += 1
    end
  end

  result << current
  result
end