Class: MovableErb::CSV

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

Overview

Loads a CSV document into an array of hashes

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#filenameObject

Returns the value of attribute filename.



44
45
46
# File 'lib/movable_erb.rb', line 44

def filename
  @filename
end

#hashesObject

Returns the value of attribute hashes.



44
45
46
# File 'lib/movable_erb.rb', line 44

def hashes
  @hashes
end

Class Method Details

.setup {|csv| ... } ⇒ MovableErb::CSV

Initializes and yields a new instance

Yields:

Returns:



50
51
52
53
54
# File 'lib/movable_erb.rb', line 50

def self.setup(&block)
  csv = self.new
  yield csv
  csv.parse!
end

Instance Method Details

#parse!MovableErb::CSV

Internally calls #to_hashes, but returns self

Returns:

See Also:



60
61
62
63
# File 'lib/movable_erb.rb', line 60

def parse!
  @hashes = self.to_hashes
  self
end

#to_hashesArray

Reads the CSV file into an array of hashes

Returns:

  • (Array)

    an Array of Hashes



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/movable_erb.rb', line 68

def to_hashes
  array_of_arrays = FasterCSV.read(filename)
  headers = array_of_arrays.shift
  headers.each { |h| h.downcase! && h.gsub!(/\s/,"_") } if headers
  hashes = Array.new(array_of_arrays.length) { Hash.new }
  array_of_arrays.each_with_index do |row,i|
    headers.each_with_index do |header, j|
      unless row[j].nil?
        hashes[i][header] = [] if hashes[i][header].nil?
        hashes[i][header] << row[j]
      end
    end
  end
  hashes
end