Class: CSVUtils::CSVIterator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/csv_utils/csv_iterator.rb

Overview

Enumerates the rows of a CSV file as hashes keyed by header, with the line number of each row.

Examples:

iterator = CSVUtils::CSVIterator.new('data.csv')
iterator.each { |row| puts "#{row.lineno}: #{row['name']}" }
iterator.select { |row| row['status'] == 'active' }

Defined Under Namespace

Classes: RowWrapper

Constant Summary collapse

BYTE_ORDER_MARKS =

Returns the byte order marks stripped from the first header, as binary strings.

Returns:

  • (Array<String>) —

    the byte order marks stripped from the first header, as binary strings

ByteOrderMark::ENCODINGS.keys.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(src_csv, csv_options = {}) ⇒ CSVIterator

A path is opened by each method call and closed when the call returns, so an idle iterator holds no file handle.

Parameters:

  • src_csv (String, CSV) —

    path or CSV to read; a CSV must support rewind and is never closed

  • csv_options (Hash) (defaults to: {}) —

    options passed to CSV.open for a path. The :encoding defaults to 'bom|utf-8' (see EncodingOptions); 'BINARY' reads bytes as is and 'Windows-1252:UTF-8' converts.



65
66
67
68
# File 'lib/csv_utils/csv_iterator.rb', line 65

def initialize(src_csv, csv_options = {})
  @src_csv = src_csv
  @csv_options = EncodingOptions.read(csv_options)
end

Class Method Details

.auto_detect(path, full_scan: false) ⇒ CSVIterator

An iterator for a path, with the separators and encoding detected by CSVUtils::CSVOptions.

Examples:

CSVUtils::CSVIterator.auto_detect('export.tsv').each { |row| puts row['name'] }

Parameters:

  • path (String)
  • full_scan (Boolean) (defaults to: false) —

    check the encoding of the whole file, not only its first megabyte

Returns:



55
56
57
58
# File 'lib/csv_utils/csv_iterator.rb', line 55

def self.auto_detect(path, full_scan: false)
  options = CSVOptions.new(path, full_scan: full_scan)
  new(path, options.to_csv_options)
end

Instance Method Details

#each(headers = nil) {|row| ... } ⇒ Enumerator?

Yields each row from the start of the file.

Parameters:

  • headers (Array<String>, nil) (defaults to: nil) —

    headers to use; by default the first row is read as the headers

Yield Parameters:

Returns:

  • (Enumerator, nil) —

    an enumerator without a block

Raises:

  • (MalformedRowError) —

    for a row CSV can't parse, with the line it starts on and #prev_row

  • (CSV::InvalidEncodingError) —

    for bytes that don't match the encoding, with their line



83
84
85
86
87
# File 'lib/csv_utils/csv_iterator.rb', line 83

def each(headers = nil, &)
  return enum_for(:each, headers) unless block_given?

  open_csv { |csv| each_row(csv, headers, &) }
end

#each_batch(batch_size = 1_000) {|batch| ... } ⇒ nil

Yields the rows in batches.

Parameters:

  • batch_size (Integer) (defaults to: 1_000) —

    rows per batch; the last batch may be smaller

Yield Parameters:

Returns:

  • (nil)


133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/csv_utils/csv_iterator.rb', line 133

def each_batch(batch_size = 1_000)
  batch = []

  process_batch_proc = proc do
    yield batch
    batch = []
  end

  each do |row|
    batch << row
    process_batch_proc.call if batch.size >= batch_size
  end

  process_batch_proc.call if batch.size.positive?

  nil
end

#headers ⇒ Array<String>

The first row, without the byte order mark.

Returns:

  • (Array<String>) —

    empty for an empty file



91
92
93
# File 'lib/csv_utils/csv_iterator.rb', line 91

def headers
  open_csv { |csv| read_headers(csv) }
end

#prev_row ⇒ Array<String>?

The raw row read before the current one (the header row for the first row), for debugging; after a full pass it's the last row.

Returns:

  • (Array<String>, nil)


73
74
75
# File 'lib/csv_utils/csv_iterator.rb', line 73

def prev_row
  @reader&.prev_row
end

#size ⇒ Integer

Number of rows after the header row.

Returns:

  • (Integer)


120
121
122
123
124
125
126
127
# File 'lib/csv_utils/csv_iterator.rb', line 120

def size
  open_csv do |csv|
    csv.shift
    cnt = 0
    cnt += 1 while csv.shift
    cnt
  end
end

#to_hash(key, value = nil) {|row| ... } ⇒ Hash

Builds a lookup hash from every row.

Parameters:

  • key (String) —

    header whose value is the hash key

  • value (String, nil) (defaults to: nil) —

    header whose value is the hash value

Yield Parameters:

  • row (RowWrapper) —

    used instead of value to compute the hash value

Returns:

  • (Hash)

Raises:



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/csv_utils/csv_iterator.rb', line 101

def to_hash(key, value = nil, &)
  file_headers = headers
  raise HeaderNotFoundError.new(key, file_headers) unless file_headers.include?(key)
  raise HeaderNotFoundError.new(value, file_headers) if value && !file_headers.include?(value)

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

  to_h do |row|
    [row[key], value_proc.call(row)]
  end
end