Advertisement
obernardovieira

Serious changes (Day 3) [SLiSW]

Jul 24th, 2015
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.48 KB | None | 0 0
  1. =begin
  2. It's day 3, and the last day of ruby! Has everyone can see, it's getting really hard! Well, if you paid attention since the begining it's not to hard. I don't know if I will share another exercise or not, but anyway. I hope everyone enjoy ;)
  3. =end
  4.  
  5. =begin
  6. the file is like this
  7. ----------------rubycsv.txt-----------
  8. one, two
  9. lions, tigers
  10. cats, dogs
  11. bird, fish
  12. --------------------------------------
  13. =end
  14.  
  15.  
  16.  
  17.  
  18.  
  19. module ActsAsCsv
  20.     def self.included(base)
  21.         base.extend ClassMethods
  22.     end
  23.     module ClassMethods
  24.         def acts_as_csv
  25.             include InstanceMethods
  26.         end
  27.     end
  28.  
  29.     module InstanceMethods  
  30.         attr_accessor :headers, :csv_contents
  31.         def initialize
  32.             read
  33.         end
  34.         def read
  35.             @csv_contents = []
  36.             filename = self.class.to_s.downcase + '.txt'
  37.             file = File.new(filename)
  38.             @headers = file.gets.chomp.split(', ')
  39.  
  40.             file.each do |row|
  41.                 @csv_contents << CsvRow.new(@headers, row.chomp.split(', '))
  42.             end
  43.         end
  44.         def each
  45.             @csv_contents.each { |row| yield row }
  46.         end
  47.  
  48.         class CsvRow
  49.             def initialize headers, row
  50.                 @headers = headers
  51.                 @row = row
  52.             end
  53.             def method_missing name, *args, &block
  54.                 index = @headers.index(name.to_s)
  55.                 if index
  56.                     @row[index]
  57.                 else
  58.                     "Can not find"
  59.                 end
  60.             end
  61.         end
  62.  
  63.     end
  64. end
  65.  
  66. class RubyCsv  # no inheritance! You can mix it in
  67.     include ActsAsCsv
  68.     acts_as_csv
  69. end
  70.  
  71. m = RubyCsv.new
  72. puts m.headers.inspect
  73. puts m.csv_contents.inspect
  74.  
  75. m.each { |row| puts "#{row.one}, #{row.two}" }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement