Created
October 3, 2011 07:35
-
-
Save japaz/1258629 to your computer and use it in GitHub Desktop.
7L7W Ruby - Day 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
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 for a given heading. | |
For example, for the file: | |
one, two | |
lions, tigers | |
allow an API that works like this: | |
csv = RubyCsv.new | |
csv.each {|row| puts row.one} | |
This should print "lions". | |
=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 | |
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 &blk | |
@csv_contents.each &blk | |
end | |
end | |
end | |
class CsvRow | |
attr_accessor :headers, :csv_contents | |
def initialize(headers=[], csv_contents=[]) | |
@csv_contents = csv_contents | |
@headers = headers | |
end | |
def method_missing name, *args | |
csv_contents[headers.index(name.to_s)] | |
end | |
end | |
class RubyCsv # no inheritance! You can mix it in | |
include ActsAsCsv | |
acts_as_csv | |
end | |
m = RubyCsv.new | |
puts m.headers.inspect | |
puts m.csv_contents.inspect | |
puts | |
puts | |
csv = RubyCsv.new | |
csv.each {|row| puts row.one} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment