Advertisement
ice09

7l7w ruby day3

Nov 4th, 2011
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.51 KB | None | 0 0
  1. # Modify the CSV application to support an each method to return a CsvRow object.
  2. # Use method_missing on that CsvRow to return the value for the column of each heading.
  3. #
  4. # Kontonummer, Name
  5. # 12144445678, ice09
  6.  
  7. class CsvRow
  8.   attr_accessor :values, :keys
  9.  
  10.   def initialize( keys, values )
  11.     @keys = keys
  12.     @values = values
  13.   end
  14.  
  15.   def method_missing(id, *args)
  16.     # if method is left out (ie. return all values), id == :to_ary
  17.     if (id==:to_ary)
  18.       then return @values
  19.       else return @values[@keys.index(id.to_s)]
  20.     end
  21.   end
  22. end
  23.  
  24. module ActsAsCsv
  25.   def self.included(base)
  26.     base.extend ClassMethods
  27.   end
  28.  
  29.   module ClassMethods
  30.     def acts_as_csv
  31.       include InstanceMethods
  32.       include Enumerable
  33.     end
  34.   end
  35.  
  36.   module InstanceMethods  
  37.     attr_accessor :headers, :csv_contents
  38.    
  39.     def each &block
  40.        @csv_contents.each{|csvRow| block.call(csvRow)}
  41.     end
  42.    
  43.     def read
  44.       @csv_contents = []
  45.       filename = self.class.to_s.downcase + '.txt'
  46.       file = File.new(filename)
  47.       @headers = file.gets.chomp.split(';').collect{|s| s.delete("\"")}
  48.      
  49.       file.each do |row|
  50.         values = row.chomp.split(';').collect{|s| s.delete("\"")}
  51.         @csv_contents << CsvRow.new(@headers, values)
  52.       end
  53.     end
  54.    
  55.     def initialize
  56.       read
  57.     end
  58.   end
  59. end
  60.  
  61. class RubyCsv  # no inheritance! You can mix it in
  62.   include ActsAsCsv
  63.   acts_as_csv
  64. end
  65.  
  66. # use it
  67. m = RubyCsv.new
  68. m.each { |it| puts it.Kontonummer }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement