Class: MovableErb::CSV
- Inherits:
-
Object
- Object
- MovableErb::CSV
- Defined in:
- lib/movable_erb.rb
Overview
Loads a CSV document into an array of hashes
Instance Attribute Summary collapse
-
#filename ⇒ Object
Returns the value of attribute filename.
-
#hashes ⇒ Object
Returns the value of attribute hashes.
Class Method Summary collapse
-
.setup {|csv| ... } ⇒ MovableErb::CSV
Initializes and yields a new instance.
Instance Method Summary collapse
-
#parse! ⇒ MovableErb::CSV
Internally calls #to_hashes, but returns self.
-
#to_hashes ⇒ Array
Reads the CSV file into an array of hashes.
Instance Attribute Details
#filename ⇒ Object
Returns the value of attribute filename.
44 45 46 |
# File 'lib/movable_erb.rb', line 44 def filename @filename end |
#hashes ⇒ Object
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
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
60 61 62 63 |
# File 'lib/movable_erb.rb', line 60 def parse! @hashes = self.to_hashes self end |
#to_hashes ⇒ Array
Reads the CSV file into 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 |