Module: CSVHash

Defined in:
lib/csv-hash.rb,
lib/csv-hash/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.from_file(file) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/csv-hash.rb', line 11

def from_file file
  num = 0
  
  data = []
  columns = []
  
  CSV.foreach(file) do |row|
    num += 1
    if num == 1
      columns = row.collect {|c| c.strip if c}
      next
    end

    hash = {}
    columns.each_with_index do |col, i|
      next unless col
      col = col ? col.strip : nil
      val = row[i] ? row[i].strip : nil

      setter = hash
      sp = col.split('__')
      sp.each_with_index do |key, j|
        if j == sp.size - 1
          setter[key] = val
        else
          setter[key] ||= {}

          setter = setter[key]
        end
      end

    end

    data << hash
  end
  
  return data, columns.compact
end

.to_string(hashes, columns) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/csv-hash.rb', line 50

def to_string hashes, columns
  rows = hashes.collect do |hash|
    vals = columns.collect do |col|
      sp = col.to_s.split('__')
      ret = hash
      sp.each do |key|
        puts key unless ret
        ret = ret[key]
      end
      ret
    end
    
    vals
  end
  
  
  csv_string = CSV.generate do |csv|
    csv << columns
    rows.each do |val|
      csv << val
    end
  end
end