Class: ExcelWalker::Reader::Hook

Inherits:
Object
  • Object
show all
Defined in:
lib/excel_walker/reader/hook.rb

Instance Method Summary collapse

Constructor Details

#initialize(condition) ⇒ Hook

Returns a new instance of Hook.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/excel_walker/reader/hook.rb', line 5

def initialize(condition)
  @matcher = case true
               when condition.is_a?(Proc)
                 condition
               when condition.is_a?(Array), condition.is_a?(Range)
                 proc { |row_num| condition.include?(row_num) }
               when condition.is_a?(Fixnum)
                 proc { |row_num| condition === row_num }
               else
                 raise ArgumentError.new('Can only take Array, Number, Range or a Block')
             end
end

Instance Method Details

#call(row, row_num, sheet, sheet_num) ⇒ Object



47
48
49
50
# File 'lib/excel_walker/reader/hook.rb', line 47

def call(row, row_num, sheet, sheet_num)
  data = extract_columns(row, row_num, sheet, sheet_num)
  @run_block[data, row_num, sheet, sheet_num]
end

#columns(cols_matcher = nil, &block) ⇒ Object Also known as: pluck_columns



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/excel_walker/reader/hook.rb', line 18

def columns(cols_matcher = nil, &block)
  cols_matcher = block if block_given?
  @cols_extractor =
      case true
        when cols_matcher.is_a?(Array)
          cols_set = Set.new(cols_matcher)
          proc { |row| row.select.with_index { |_, idx| cols_set.include?(idx + 1) } }
        when cols_matcher.is_a?(Fixnum)
          proc { |row| row[cols_matcher - 1] }
        when cols_matcher.is_a?(Range)
          proc { |row| row[(cols_matcher.min - 1)..(cols_matcher.max - 1)] }
        when cols_matcher.is_a?(Proc)
          proc { |row| cols_matcher[row] }
        else
          raise ArgumentError.new('Can only take Array, Number, Range or a Block')
      end
  self
end

#match?(row_num, sheet_num = nil) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/excel_walker/reader/hook.rb', line 43

def match?(row_num, sheet_num = nil)
  @matcher[row_num, sheet_num]
end

#run(&block) ⇒ Object



39
40
41
# File 'lib/excel_walker/reader/hook.rb', line 39

def run(&block)
  @run_block = block
end