Class: SCSV
- Inherits:
-
Object
- Object
- SCSV
- Defined in:
- lib/scsv.rb
Overview
for COMMA separated file
Direct Known Subclasses
Constant Summary collapse
- VERSION =
'0.2.0'
- DEFAULT_OPTIONS =
{ :col_sep => ",", :row_sep => "\n", :header => true, }
Class Method Summary collapse
- .parse(filename, options = {}, &block) ⇒ Object
- .parse_with_block(filename, options, &block) ⇒ Object
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, = {}, &block) = DEFAULT_OPTIONS.merge() if block_given? parse_with_block(filename, , &block) else rows = [] parse_with_block(filename, ) 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, , &block) Kernel.open(filename, "r") do |f| header = nil if [:header] && [:header].is_a?(Array) # using passed Array header = [:header] elsif [:header] # using file's first row header = f.gets.gsub(/\n/, "").split([:col_sep]) end # read lines f.each do |line| tokens = line.gsub(/\n/, "").split([: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 |