Class: Abtab::Driver::CSVDriver

Inherits:
Abtab::Driver show all
Defined in:
lib/abtab/drivers/csv_driver.rb

Instance Method Summary collapse

Methods inherited from Abtab::Driver

#import, #url_parse

Constructor Details

#initialize(url) ⇒ CSVDriver

Returns a new instance of CSVDriver.



5
6
7
8
9
10
11
# File 'lib/abtab/drivers/csv_driver.rb', line 5

def initialize url
  options = {
    "quote_char" => '"',
    "col_sep"    => ','
  }
  @schema, @file, @options = url_parse url, options
end

Instance Method Details

#closeObject



39
40
41
42
43
44
# File 'lib/abtab/drivers/csv_driver.rb', line 39

def close
  if @read_fh
    @read_fh.close
    @read_fh = nil
  end
end

#columnsObject



28
29
30
# File 'lib/abtab/drivers/csv_driver.rb', line 28

def columns
  @columns
end

#next_recordObject



32
33
34
35
36
37
# File 'lib/abtab/drivers/csv_driver.rb', line 32

def next_record
  return nil if @read_fh.eof?
  line = @read_fh.readline
  line.chomp!
  FasterCSV.parse(line, :quote_char => @options["quote_char"], :col_sep => @options["col_sep"]).first
end

#open_for_readingObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/abtab/drivers/csv_driver.rb', line 13

def open_for_reading
  if @file == '/dev/stdin'
    @read_fh = $stdin
  else
    if !File.exists? @file
      raise "Error: can not open for reading, file does not exist: #{@file}"
    end
    @read_fh = File.open(@file,'r')
  end

  header_line = @read_fh.readline
  header_line.chomp!
  @columns = FasterCSV.parse(header_line, :quote_char => @options["quote_char"], :col_sep => @options["col_sep"]).first
end

#open_for_writingObject



46
47
48
49
50
51
52
53
54
# File 'lib/abtab/drivers/csv_driver.rb', line 46

def open_for_writing
  # NB: truncates the output file
  if @file == '/dev/stdout'
    @write_fn = $stdout
  else
    @write_fh = File.open(@file,'w')
  end
  set_columns(@columns) if @columns && !@columns.empty
end

#set_columns(cols) ⇒ Object



61
62
63
64
# File 'lib/abtab/drivers/csv_driver.rb', line 61

def set_columns cols
  @columns = cols
  write_record @columns
end

#write_record(rec) ⇒ Object



56
57
58
59
# File 'lib/abtab/drivers/csv_driver.rb', line 56

def write_record rec
  line = rec.to_csv(:quote_char => @options["quote_char"], :col_sep => @options["col_sep"])
  @write_fh.puts line
end