Class: Xls::Enumerator

Inherits:
Object
  • Object
show all
Defined in:
lib/xls/enumerator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Enumerator

Constructor



9
10
11
12
# File 'lib/xls/enumerator.rb', line 9

def initialize(options={})
  self.selection = options[:selection]
  self.proc = options[:proc]
end

Instance Attribute Details

#actionObject

The action to perform on each cell of data (:none, :map, :select, :reject).



22
23
24
# File 'lib/xls/enumerator.rb', line 22

def action
  @action
end

#procObject

The proc to run on each cell.



28
29
30
# File 'lib/xls/enumerator.rb', line 28

def proc
  @proc
end

#selectionObject

The selection to enumerate over.



25
26
27
# File 'lib/xls/enumerator.rb', line 25

def selection
  @selection
end

#use_headersObject

A flag stating if headers should be used.



31
32
33
# File 'lib/xls/enumerator.rb', line 31

def use_headers
  @use_headers
end

Instance Method Details

#cell_binding(text, col, row, header) ⇒ Object

Returns the context in which cell procs are run.



80
81
82
# File 'lib/xls/enumerator.rb', line 80

def cell_binding(text, col, row, header)
  return binding
end

#process(input) ⇒ Object

Executes a proc on each cell in a selection.

Parameters:

  • input (Workbook)

    The input workbook.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/xls/enumerator.rb', line 43

def process(input)
  # Loop over each worksheet.
  (0...input.sheet_count).each do |sheet_index|
    sheet = input.worksheet(sheet_index)
    headers = sheet.row(0)
    
    # Loop over each row.
    sheet.each(use_headers ? 1 : 0) do |row|
      next unless selection.nil? || selection.rows.nil? || selection.rows.cover?(row.idx)
      
      # Loop over each cell.
      row.each_with_index do |cell, col_index|
        next unless selection.nil? || selection.columns.nil? || selection.columns.cover?(col_index)
        
        # Run proc and retrieve the results.
        header = (use_headers ? headers[col_index].to_s : '')
        result = cell_binding(cell.to_s, col_index, row.idx, header).eval(proc)
        
        # Perform an action if one is specified.
        case action
        when :map then row[col_index] = result.to_s
        when :select then row[col_index] = '' unless result
        when :reject then row[col_index] = '' if result
        end
      end
    end
  end
  
  return nil
end