Class: Abtab::Driver::TabDriver

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

Instance Method Summary collapse

Methods inherited from Abtab::Driver

#import, #url_parse

Constructor Details

#initialize(url) ⇒ TabDriver

Returns a new instance of TabDriver.



3
4
5
6
7
# File 'lib/abtab/drivers/tab_driver.rb', line 3

def initialize url
  @options = {}
  @options["col_sep"] = "\t"
  @schema, @file, @options = url_parse url, @options
end

Instance Method Details

#closeObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/abtab/drivers/tab_driver.rb', line 50

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

#columnsObject



41
42
43
# File 'lib/abtab/drivers/tab_driver.rb', line 41

def columns
  @columns
end

#format_rec(r) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/abtab/drivers/tab_driver.rb', line 31

def format_rec r
  r.map do |f|
    f = f.to_s
    f.gsub! "\t", "\\t"
    f.gsub! "\n", "\\n"
    f.gsub! "\r", "\\r"
    f
  end.join(@options["col_sep"])
end

#next_recordObject



45
46
47
48
# File 'lib/abtab/drivers/tab_driver.rb', line 45

def next_record
  return nil if @read_fh.eof?
  parse_line @read_fh.readline
end

#open_for_readingObject



9
10
11
12
13
14
15
16
17
# File 'lib/abtab/drivers/tab_driver.rb', line 9

def open_for_reading
  if !File.exists? @file
    raise "Error: can not open for reading, file does not exist: #{@file}"
  end

  @read_fh = File.open(@file,'r')
  header_line = @read_fh.readline
  @columns = parse_line header_line
end

#open_for_writingObject



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

def open_for_writing 
  @write_fh = File.open(@file, 'w')
  set_columns(@columns) if @columns && !@columns.empty
end

#parse_line(l) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/abtab/drivers/tab_driver.rb', line 19

def parse_line l
  l.chomp!
  r = l.split(@options["col_sep"]).map do |f|
    f.gsub! "\\t", "\t"
    f.gsub! "\\n", "\n"
    f.gsub! "\\r", "\r"
    f
  end
  r[0].chomp!
  r
end

#set_columns(cols) ⇒ Object



70
71
72
73
74
# File 'lib/abtab/drivers/tab_driver.rb', line 70

def set_columns cols
  @columns = cols
  write_record @columns
  
end

#write_record(rec) ⇒ Object



66
67
68
# File 'lib/abtab/drivers/tab_driver.rb', line 66

def write_record rec
  @write_fh.puts format_rec(rec)
end