Class: Spreadshot::Backends::RubyXLBackend

Inherits:
ReaderBackend show all
Defined in:
lib/spreadshot/backends/ruby_xl_backend.rb

Overview

Adapter for the RubyXL Gem (https://github.com/weshatheleopard/rubyXL)

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RubyXLBackend

Returns a new instance of RubyXLBackend (See Spreadshot::ReaderBackends::ReaderBackend)

Options Hash (options):

  • :headers (Boolean)

    Specifies whether the spreadsheet to be read contains headers. Defaults to true

  • :worksheet_index (Integer)

    The index of the worksheet to be read. Used for the RubyXL backend. Defaults to 0

  • :cell_index_to_field_mapper (Hash)

    A hash which maps each cell in a row of the spreadsheet to a key in the hash created for that row. Must be provided

Raises:

  • (ArgumentError)

    if cell_index_to_field_mapper option is not provided

  • (ArgumentError)

    if cell_index_to_field_mapper option is not a Hash


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/spreadshot/backends/ruby_xl_backend.rb', line 24

def initialize(options = {})
  options ||= {}
  super(options)

  begin
    @worksheet_index = Integer(options[:worksheet_index])
  rescue TypeError
    @worksheet_index = 0
  end
  
  begin
    @cell_index_to_field_mapper = Hash(options[:cell_index_to_field_mapper])
  rescue TypeError
    @cell_index_to_field_mapper = options[:cell_index_to_field_mapper]
  end

  raise ArgumentError, 'cell_index_to_field_mapper is invalid' unless @cell_index_to_field_mapper.is_a?(Hash)
  raise ArgumentError, 'cell_index_to_field_mapper cannot be empty' if @cell_index_to_field_mapper.empty?
end

Instance Method Details

#read(path_to_spreadsheet) {|row_index, row_data| ... } ⇒ Object

Reads data from the specified spreadsheet (See Spreadshot::ReaderBackends::ReaderBackend)

Yields:

  • (row_index, row_data)

Yield Parameters:

  • row_index (Integer)

    The index of the current row being read. The first row has an index of 1

  • row_data (Hash)

    A hash representation of the data read from the current row

Raises:


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/spreadshot/backends/ruby_xl_backend.rb', line 59

def read(path_to_spreadsheet)
  worksheet = RubyXL::Parser.parse(path_to_spreadsheet)[@worksheet_index]
  headers = @headers
  
  worksheet.each do |row|
    if headers
      headers = false
      next
    end
    
    cell_index = 0
    current_row_data = {}  
    
    row && row.cells.each do |cell|
      val = cell && cell.value
    
      if @cell_index_to_field_mapper[cell_index]
        current_row_data[@cell_index_to_field_mapper[cell_index]] = val
      end
    
      cell_index += 1
    end
    
    yield(@current_row_index, current_row_data)
    @current_row_index += 1
  end
  
  return nil
rescue => e
  raise Spreadshot::ReaderError, e.message
end