Modify the CSV application to support an each method to return a CsvRow object. Use method_missing on that CsvRow to return the value for a given heading.
module ActsAsCsv def self.included (base) base.extend ClassMethods end module ClassMethods def acts_as_csv include InstanceMethods end module InstanceMethods class CsvRow def initialize (headers, row) @headers = headers @row = row end def method_missing (name, *args) index = @headers.index(name.to_s) @row[index] unless index.nil? end end def read @csv_contents = [] filename = self.class.to_s.downcase + '.txt' file = File.new(filename) @headers = file.gets.chomp.split(', ') file.each do |row| @csv_contents << CsvRow.new(headers, row.chomp.split(', ')) end end attr_accessor :headers, :csv_contents def initialize read end def each (&block) @csv_contents.each(&block) end end end end
No comments:
Post a Comment