Friday, March 2, 2012

Seven Languages in Seven Weeks - Ruby Day 3 Self Study

Hi again. Here's the self-study section for day 3 from the book Seven Languages in Seven Weeks, the last one about ruby.

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