Class: Importer::ExcelReader

Inherits:
DataReader show all
Defined in:
lib/iron/import/excel_reader.rb

Overview

Uses the Roo gem to read in .xls files

Direct Known Subclasses

XlsReader, XlsxReader

Instance Attribute Summary

Attributes inherited from DataReader

#format

Instance Method Summary collapse

Methods inherited from DataReader

#add_error, #add_exception, for_format, for_path, for_source, for_stream, is_stream?, #load, #load_each, #parse_value, path_from_stream, #supports?, #supports_file!, #supports_file?, #supports_stream!, #supports_stream?, verify_nokogiri!, verify_roo!

Constructor Details

#initialize(importer, format) ⇒ ExcelReader

Returns a new instance of ExcelReader.



6
7
8
9
# File 'lib/iron/import/excel_reader.rb', line 6

def initialize(importer, format)
  super(importer, format)
  supports_file!
end

Instance Method Details

#include_sheet?(scopes, name, index) ⇒ Boolean

When true, the given sheet name or zero-based index is a match with our id.

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
63
64
65
# File 'lib/iron/import/excel_reader.rb', line 55

def include_sheet?(scopes, name, index)
  return true if scopes.nil? || scopes.empty?
  scopes.each do |scope|
    if scope.is_a?(Fixnum)
      return true if scope.to_i == index+1
    else
      return true if scope.to_s.downcase == name.downcase
    end
  end
  false
end

#init_source(mode, source) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/iron/import/excel_reader.rb', line 11

def init_source(mode, source)
  if mode == :file
    if @format == :xls
      @spreadsheet = Roo::Excel.new(source, :file_warning => :ignore)
      true
    elsif @format == :xlsx
      @spreadsheet = Roo::Excelx.new(source, :file_warning => :ignore)
      true
    else
      add_error("Unknown format for Excel file: :#{@format}")
      false
    end
  else
    add_error("Unsupported #{@format.to_s.upcase} mode: #{mode}")
    false
  end
rescue Exception => e
  add_exception(e)
  false
end

#load_raw(scopes, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/iron/import/excel_reader.rb', line 32

def load_raw(scopes, &block)
  @spreadsheet.sheets.each_with_index do |name, index|
    # See if this sheet's name or index matches the requested sheet definition
    if include_sheet?(scopes, name, index)
      # Extract our raw data
      raw_rows = []
      @spreadsheet.sheet(name).each_with_index do |row, line|
        raw_rows << row
      end
      # Yield our raw rows for this sheet
      found = block.call(raw_rows)
      # If we've found a working sheet, stop
      return if found
    end
  end

rescue Exception => e
  # Not sure why we'd get here, but we strive for error-freedom here, yessir.
  add_exception(e)
end