Class: SCSV

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

Overview

for COMMA separated file

Direct Known Subclasses

STSV

Constant Summary collapse

VERSION =
'0.2.0'
DEFAULT_OPTIONS =
{
  :col_sep  => ",",
  :row_sep  => "\n",
  :header   => true,
}

Class Method Summary collapse

Class Method Details

.parse(filename, options = {}, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/scsv.rb', line 16

def self.parse(filename, options = {}, &block)
  options = DEFAULT_OPTIONS.merge(options)
  if block_given?
    parse_with_block(filename, options, &block)
  else
    rows = []
    parse_with_block(filename, options) do |row|
      rows << row
    end
    return rows
  end
end

.parse_with_block(filename, options, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/scsv.rb', line 29

def self.parse_with_block(filename, options, &block)
  Kernel.open(filename, "r") do |f|
    header = nil
    if options[:header] && options[:header].is_a?(Array)
      # using passed Array
      header = options[:header]
    elsif options[:header]
      # using file's first row
      header = f.gets.gsub(/\n/, "").split(options[:col_sep])
    end
    # read lines
    f.each do |line|
      tokens = line.gsub(/\n/, "").split(options[:col_sep])
      row = tokens
      if header
        row = {}
        tokens.each_with_index do |i, idx|
          row[header[idx]] = i
        end
      end
      yield(row)
    end
  end
end