4
5
6
7
8
9
10
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
# File 'lib/better_csv.rb', line 4
def self.parse(str)
in_literal = false
csv = Array.new
line = []
token = ""
back = ""
current = ""
first = true
str.each_char do |c|
current = c
if first
back = current
if c == '"'
in_literal = true
elsif c == ','
line << ""
else
token << c
end
first = false
next
end
in_literal = !in_literal if current == '"' and not back == '\\'
if current == ',' and not in_literal
line << token
token = ""
next
end
if current == "\n" and not in_literal
line << token
csv << line
token = ""
yield(line) if block_given?
line = Array.new
next
end
token << c unless current == '"' and not back == '\\'
back = current
end
if token.size > 0
line << token
yield(line) if block_given?
elsif current == ','
line << ''
end
csv << line if line.size > 0
return csv
rescue => e
STDERR.puts e
STDERR.puts e.backtrace
end
|