Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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 the column of each heading.
- #
- # Kontonummer, Name
- # 12144445678, ice09
- class CsvRow
- attr_accessor :values, :keys
- def initialize( keys, values )
- @keys = keys
- @values = values
- end
- def method_missing(id, *args)
- # if method is left out (ie. return all values), id == :to_ary
- if (id==:to_ary)
- then return @values
- else return @values[@keys.index(id.to_s)]
- end
- end
- end
- module ActsAsCsv
- def self.included(base)
- base.extend ClassMethods
- end
- module ClassMethods
- def acts_as_csv
- include InstanceMethods
- include Enumerable
- end
- end
- module InstanceMethods
- attr_accessor :headers, :csv_contents
- def each &block
- @csv_contents.each{|csvRow| block.call(csvRow)}
- end
- def read
- @csv_contents = []
- filename = self.class.to_s.downcase + '.txt'
- file = File.new(filename)
- @headers = file.gets.chomp.split(';').collect{|s| s.delete("\"")}
- file.each do |row|
- values = row.chomp.split(';').collect{|s| s.delete("\"")}
- @csv_contents << CsvRow.new(@headers, values)
- end
- end
- def initialize
- read
- end
- end
- end
- class RubyCsv # no inheritance! You can mix it in
- include ActsAsCsv
- acts_as_csv
- end
- # use it
- m = RubyCsv.new
- m.each { |it| puts it.Kontonummer }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement