Module: CSVHelper

Defined in:
lib/hammer_cli_import/csvhelper.rb

Defined Under Namespace

Classes: CSVHelperError

Class Method Summary collapse

Class Method Details

.csv_each(filename, headers) ⇒ Object

Raises:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/hammer_cli_import/csvhelper.rb', line 34

def self.csv_each(filename, headers)
  raise CSVHelperError, 'Expecting block' unless block_given?
  reader = CSV.open(filename, 'r')
  real_header = reader.shift
  raise CSVHelperError, "No header in #{filename}" if real_header.nil?
  real_header_length = real_header.length
  to_discard = real_header - headers
  headers.each do |col|
    raise CSVHelperError, "Column #{col} expected in #{filename}" unless real_header.include? col
  end
  reader.each do |row|
    raise CSVHelperError, "Broken CSV in #{filename}: #{real_header_length} columns expected but found #{row.length}" \
      unless row.length == real_header_length
    data = Hash[real_header.zip row]
    to_discard.each { |key| data.delete key }
    class << data
      def[](key)
        raise CSVHelperError, "Referencing undeclared key: #{key}" unless key? key
        super
      end
    end
    yield data
  end
end

.csv_missing_columns(filename, headers) ⇒ Object

Returns missing columns



27
28
29
30
31
32
# File 'lib/hammer_cli_import/csvhelper.rb', line 27

def self.csv_missing_columns(filename, headers)
  reader = CSV.open(filename, 'r')
  real_header = reader.shift
  reader.close
  headers - real_header
end

.csv_write_hashes(filename, headers, hashes) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/hammer_cli_import/csvhelper.rb', line 59

def self.csv_write_hashes(filename, headers, hashes)
  CSV.open(filename, 'wb') do |csv|
    csv << headers
    hashes.each do |hash|
      csv << headers.collect { |key| hash[key] }
    end
  end
end