Created
November 7, 2011 23:16
-
-
Save macosgrove/1346504 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
module ActsAsCsv | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def acts_as_csv | |
include InstanceMethods | |
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 << row.chomp.split(', ') | |
end | |
end | |
attr_accessor :headers, :csv_contents | |
def initialize | |
read | |
end | |
end | |
end | |
class RubyCsv # no inheritance! You can mix it in | |
include ActsAsCsv | |
acts_as_csv | |
def printAll | |
@csv_contents.each {|row| p row} | |
end | |
def each (&block) | |
@csv_contents.each {|row| yield Row.new(@headers, row)} | |
end | |
end | |
class Row | |
attr_accessor :headers, :row | |
def initialize(headers, row) | |
@headers = headers | |
@row = row | |
end | |
def method_missing name | |
@row[@headers.index(name.to_s)] | |
end | |
end | |
csv = RubyCsv.new | |
csv.printAll | |
csv.each do |row| | |
puts "One = #{row.one} Two = #{row.two} Three = #{row.three}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't handle invalid headers