Skip to content

Instantly share code, notes, and snippets.

@ngm
Created November 29, 2011 23:09
Show Gist options
  • Save ngm/1407073 to your computer and use it in GitHub Desktop.
Save ngm/1407073 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Ruby - Day 3 - CsvRow
module ActsAsCsv
include Enumerable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
def each
csv_contents.each do |row|
yield CsvRow.new(row)
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 << row.chomp.split(', ')
end
end
attr_accessor :headers, :csv_contents
def initialize
read
end
end
end
class CsvRow
attr_accessor :row
def initialize(row)
@row = row
end
def method_missing name, *args
result = @row[0] if name.to_s.chomp == "one"
result = @row[1] if name.to_s == "two"
result
end
end
class RubyCsv
include ActsAsCsv
acts_as_csv
end
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