Class: Abtab::Driver::XlsDriver

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

Instance Method Summary collapse

Methods inherited from Abtab::Driver

#import, #url_parse

Constructor Details

#initialize(url) ⇒ XlsDriver

Returns a new instance of XlsDriver.



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

def initialize url
  @read_index = 1
  @read_worksheet_index = 0
  @write_index = 0
  @options = {}
  @options["client_encoding"] = "UTF-8"
  @schema, @file, @options = url_parse url, @options
end

Instance Method Details

#closeObject



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

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

#columnsObject



37
38
39
# File 'lib/abtab/drivers/xls_driver.rb', line 37

def columns
  @columns
end

#next_recordObject



41
42
43
44
45
46
47
48
49
# File 'lib/abtab/drivers/xls_driver.rb', line 41

def next_record
  if @read_index >= @read_fh.count
    line = nil
  else
    line = parse_line @read_fh.row @read_index
    @read_index += 1
  end
  line
end

#open_for_readingObject



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

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

  book = Spreadsheet.open @file
  if @options["worksheet"]
    unless book.worksheets.detect { |ws| ws.name == @options["worksheet"] }
      raise "Error: specified worksheet (#{@options['worksheet']}) not found in workbook."
    end
    @read_fh = book.worksheet @options["worksheet"]
  else
    @read_fh = book.worksheet 0
  end

  header_line = @read_fh.row 0
  @columns = parse_line header_line
end

#open_for_writingObject



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

def open_for_writing
  @write_fh = Spreadsheet::Workbook.new
  @write_sheet = @write_fh.create_worksheet
  set_columns(@columns) if @columns && !@columns.empty
end

#parse_line(l) ⇒ Object



32
33
34
35
# File 'lib/abtab/drivers/xls_driver.rb', line 32

def parse_line l
  # For now, coerce everything string
  l.collect { |v| v.to_s }
end

#set_columns(cols) ⇒ Object



72
73
74
75
# File 'lib/abtab/drivers/xls_driver.rb', line 72

def set_columns cols
  @columns = cols
  write_record @columns
end

#write_record(rec) ⇒ Object



67
68
69
70
# File 'lib/abtab/drivers/xls_driver.rb', line 67

def write_record rec
  @write_sheet.row(@write_index).replace rec
  @write_index += 1
end