Class: Dap::Input::InputCSV

Inherits:
Object
  • Object
show all
Includes:
FileSource
Defined in:
lib/dap/input/csv.rb

Overview

CSV

Instance Attribute Summary collapse

Attributes included from FileSource

#fd

Instance Method Summary collapse

Methods included from FileSource

#close, #open

Constructor Details

#initialize(args) ⇒ InputCSV

Returns a new instance of InputCSV.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/dap/input/csv.rb', line 15

def initialize(args)
  self.headers = []

  fname = args.shift
  self.open(fname)

  args.each do |arg|
    if arg =~ /^header=(.*)/
      val =$1
      self.has_header = !! (val =~ /^y|t|1/i)
    end
  end

  if self.has_header
    data = read_record
    unless (data == :eof or data == :empty)
      self.headers = data.values.map{|x| x.to_s.strip }
    end
  end
end

Instance Attribute Details

#has_headerObject

Returns the value of attribute has_header.



13
14
15
# File 'lib/dap/input/csv.rb', line 13

def has_header
  @has_header
end

#headersObject

Returns the value of attribute headers.



13
14
15
# File 'lib/dap/input/csv.rb', line 13

def headers
  @headers
end

Instance Method Details

#read_recordObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/dap/input/csv.rb', line 36

def read_record
  res = {}
  line = self.fd.readline rescue nil
  return Error::EOF unless line
  line.force_encoding('BINARY')

  # Short-circuit the slow CSV parser if the data does not contain double quotes
  arr = line.index('"') ?
    ( CSV.parse(line) rescue nil ) :
    [ line.split(',').map{|x| x.strip } ]

  return Error::Empty unless arr
  cnt = 0
  arr.first.each do |x|
    cnt += 1
    if x.to_s.length > 0
      res[headers[cnt-1] || cnt.to_s] = x
    end
  end
  res
end