Class: Typingpool::Filer::CSV

Inherits:
Typingpool::Filer show all
Includes:
Enumerable
Defined in:
lib/typingpool/filer/csv.rb

Overview

Convenience wrapper for CSV files. Makes them Enumerable, so you can iterate through rows with each, map, select, etc. You can also modify in place with each!. See Filer base class for other methods.

Instance Attribute Summary

Attributes inherited from Typingpool::Filer

#path

Instance Method Summary collapse

Methods inherited from Typingpool::Filer

#<=>, #as, #dir, #initialize, #mv!, #to_s, #to_stream

Methods included from Utility::Castable

#as, included

Constructor Details

This class inherits a constructor from Typingpool::Filer

Instance Method Details

#eachObject

Enumerate through the rows, with each row represented by a hash.



43
44
45
46
47
# File 'lib/typingpool/filer/csv.rb', line 43

def each
  read.each do |row|
    yield row
  end
end

#each!Object

Same as each, but any changes to the rows will be written back out to the underlying CSV file.



51
52
53
54
# File 'lib/typingpool/filer/csv.rb', line 51

def each!
  #each_with_index doesn't return the array, so we have to use each
  write(each{|hash| yield(hash) })
end

#readObject

Reads into an array of hashes, with hash keys determined by the first row of the CSV file. Parsing rules are the default for CSV.parse.



15
16
17
18
19
20
# File 'lib/typingpool/filer/csv.rb', line 15

def read
  raw = super or return []
  rows = ::CSV.parse(raw.to_s)
  headers = rows.shift or raise Error::File, "No CSV at #{@path}"
  rows.map{|row| Utility.array_to_hash(row, headers) }
end

#write(hashes, headers = hashes.map{|h| h.keys}.flatten.uniq) ⇒ Object

Takes array of hashes followed by optional list of keys (by default keys are determined by looking at all the hashes). Lines are written per the defaults of CSV.generate_line.



26
27
28
29
30
31
32
33
# File 'lib/typingpool/filer/csv.rb', line 26

def write(hashes, headers=hashes.map{|h| h.keys}.flatten.uniq)
  super(
        ::CSV.generate_line(headers, :encoding => @encoding) + 
        hashes.map do |hash|
          ::CSV.generate_line(headers.map{|header| hash[header] }, :encoding => @encoding)
        end.join
        )
end

#write_arrays(arrays, headers) ⇒ Object

Takes an array of arrays, corresponding to the rows, and a list of headers/keys to write at the top.



37
38
39
# File 'lib/typingpool/filer/csv.rb', line 37

def write_arrays(arrays, headers)
  write(arrays.map{|array| Utility.array_to_hash(array, headers) }, headers)
end