Module: RemoteTable::ProcessedByRoo

Defined in:
lib/remote_table/processed_by_roo.rb

Overview

Mixed in to process XLS, XLSX, and ODS with the Roo library.

Constant Summary collapse

TAG =
/<[^>]+>/
BLANK =
''

Instance Method Summary collapse

Instance Method Details

#_eachObject

Yield each row using Roo.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/remote_table/processed_by_roo.rb', line 8

def _each
  require 'roo'

  spreadsheet = roo_class.new local_copy.path, :file_warning => :ignore
  if sheet
    spreadsheet.default_sheet = sheet
  end

  first_row = if crop
    crop.first + 1
  else
    skip + 1
  end

  last_row = if crop
    crop.last
  else
    spreadsheet.last_row
  end

  if not headers

    # create an array to represent this row
    (first_row..last_row).each do |y|
      some_value_present = false
      output = (1..spreadsheet.last_column).map do |x|
        memo = spreadsheet.cell(y, x).to_s.dup
        memo = assume_utf8 memo
        memo.gsub! TAG, BLANK
        memo.strip!
        if not some_value_present and not keep_blank_rows and memo.present?
          some_value_present = true
        end
        memo
      end
      if keep_blank_rows or some_value_present
        yield output
      end
    end

  else

    # create a hash to represent this row
    current_headers = ::ActiveSupport::OrderedHash.new
    i = 0
    if headers == :first_row
      (1..spreadsheet.last_column).each do |x|
        v = spreadsheet.cell(first_row, x)
        if v.blank?
          # then look up one
          v = spreadsheet.cell(first_row - 1, x)
        end
        if v.present?
          v = assume_utf8 v
          # 'foobar' is found at column 6
          current_headers[v] = x
        else
          current_headers["untitled_#{i+=1}"] = x
        end
      end
      # "advance the cursor"
      first_row += 1
    else
      headers.each_with_index do |k, i|
        current_headers[k] = i + 1
      end
    end
    (first_row..last_row).each do |y|
      some_value_present = false
      output = ::ActiveSupport::OrderedHash.new
      current_headers.each do |k, x|
        memo = spreadsheet.cell(y, x).to_s.dup
        memo = assume_utf8 memo
        memo.gsub! TAG, BLANK
        memo.strip!
        if not some_value_present and not keep_blank_rows and memo.present?
          some_value_present = true
        end
        output[k] = memo
      end
      if keep_blank_rows or some_value_present
        yield output
      end
    end

  end
ensure
  local_copy.cleanup
end