class CSVUtils::CSVIterator

Search a CSV given a series of steps

Attributes

prev_row[R]

Public Class Methods

new(src_csv, csv_options = {}) click to toggle source
# File lib/csv_utils/csv_iterator.rb, line 24
def initialize(src_csv, csv_options = {})
  @src_csv = CSVUtils::CSVWrapper.new(src_csv, 'rb', csv_options)
end

Public Instance Methods

each(headers = nil) { |create| ... } click to toggle source
# File lib/csv_utils/csv_iterator.rb, line 28
def each(headers = nil)
  @src_csv.rewind

  lineno = 0
  unless headers
    headers = @src_csv.shift
    strip_bom!(headers[0])
    lineno += 1
  end

  @prev_row = nil
  while (row = @src_csv.shift)
    lineno += 1
    yield RowWrapper.create(headers, row, lineno)
    @prev_row = row
  end
end
headers() click to toggle source
# File lib/csv_utils/csv_iterator.rb, line 46
def headers
  @src_csv.rewind
  headers = @src_csv.shift
  strip_bom!(headers[0])
  headers
end
to_hash(key, value = nil) { |row| ... } click to toggle source
# File lib/csv_utils/csv_iterator.rb, line 53
def to_hash(key, value = nil)
  raise("header #{key} not found in #{headers}") unless headers.include?(key)
  raise("headers #{value} not found in #{headers}") if value && !headers.include?(value)

  value_proc =
    if value
      proc { |row| row[value] }
    else
      proc { |row| yield(row) }
    end

  each_with_object({}) do |row, hsh|
    hsh[row[key]] = value_proc.call(row)
  end
end

Private Instance Methods

strip_bom!(col) click to toggle source
# File lib/csv_utils/csv_iterator.rb, line 71
def strip_bom!(col)
  col.sub!("\xEF\xBB\xBF".force_encoding('ASCII-8BIT'), '')
end