Class: CsvHashReader

Inherits:
Object
  • Object
show all
Defined in:
lib/csvreader/reader.rb

Class Method Summary collapse

Class Method Details

.foreach(path, sep: Csv.config.sep, headers: nil, &block) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/csvreader/reader.rb', line 215

def self.foreach( path, sep: Csv.config.sep, headers: nil, &block )

  ## pass in headers as array e.g. ['A', 'B', 'C']
  names = headers ? headers : nil

  CsvReader.foreach( path ) do |values|     # sep: sep
    if names.nil?
      names = values   ## store header row / a.k.a. field/column names
    else
      record = names.zip( values ).to_h    ## todo/fix: check for more values than names/headers!!!
      block.call( record )
    end
  end
end

.header(path, sep: Csv.config.sep) ⇒ Object

add header too? why? why not?



231
232
233
234
# File 'lib/csvreader/reader.rb', line 231

def self.header( path, sep: Csv.config.sep )   ## add header too? why? why not?
  ## same as "classic" header method - delegate/reuse :-)
  CsvReader.header( path, sep: sep )
end

.parse(txt, sep: Csv.config.sep, headers: nil) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/csvreader/reader.rb', line 191

def self.parse( txt, sep: Csv.config.sep, headers: nil )

  ## pass in headers as array e.g. ['A', 'B', 'C']
  names = headers ? headers : nil

  records = []
  CsvReader.parse_lines( txt ) do |values|     # sep: sep
    if names.nil?
      names = values   ## store header row / a.k.a. field/column names
    else
      record = names.zip( values ).to_h    ## todo/fix: check for more values than names/headers!!!
      records << record
    end
  end
  records
end

.read(path, sep: Csv.config.sep, headers: nil) ⇒ Object



209
210
211
212
# File 'lib/csvreader/reader.rb', line 209

def self.read( path, sep: Csv.config.sep, headers: nil )
  txt = File.open( path, 'r:bom|utf-8' ).read
  parse( txt, sep: sep, headers: headers )
end