Skip to content

Instantly share code, notes, and snippets.

@jomontanari
Created November 5, 2011 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jomontanari/1342135 to your computer and use it in GitHub Desktop.
Save jomontanari/1342135 to your computer and use it in GitHub Desktop.
Ruby - Day 3
class CsvRow
def initialize(headers, row)
@headers = headers
@row = row
end
def method_missing name
unless @headers.index(name.to_s).nil?
@row[@headers.index(name.to_s)]
end
end
end
class ActsAsCsv
def self.acts_as_csv
define_method 'read' do
file = File.new(self.class.to_s.downcase + ".txt")
@headers = file.gets.chomp.split(', ')
file.each do |row|
@result << row.chomp.split(', ')
end
end
define_method 'headers' do
@headers
end
define_method 'csv_contents' do
@result
end
define_method 'initialize' do
@result = []
read
end
define_method 'each' do |&block|
@result.each { |row| block.call CsvRow.new(@headers, row) }
end
end
end
class RubyCsv < ActsAsCsv
acts_as_csv
end
m = RubyCsv.new
puts m.headers.inspect
puts m.csv_contents.inspect
m.each { |row| puts row.one}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment