module RemoteTable::ProcessedByRoo

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

Constants

BLANK
TAG

Public Instance Methods

_each() { |output| ... } click to toggle source

Yield each row using Roo.

# 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 or headers == true
      (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
          if stop_after_untitled_headers and i > stop_after_untitled_headers
            break
          end
          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