Skip to content

Instantly share code, notes, and snippets.

@macosgrove
Created November 7, 2011 23:16
Show Gist options
  • Save macosgrove/1346504 to your computer and use it in GitHub Desktop.
Save macosgrove/1346504 to your computer and use it in GitHub Desktop.
7L7W Ruby Day 3
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
@macosgrove
Copy link
Author

Doesn't handle invalid headers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment