Skip to content

Instantly share code, notes, and snippets.

@devnoo
Created November 15, 2011 19:49
Show Gist options
  • Save devnoo/1368106 to your computer and use it in GitHub Desktop.
Save devnoo/1368106 to your computer and use it in GitHub Desktop.
ActsAsCsv
class ActsAsCsv
def read
file = File.new(self.class.to_s.downcase + '.txt')
@headers = file.gets.chomp.split(', ')
file.each do |row|
@result << CsvRow.new(@headers, row.chomp.split(', '))
end
end
def headers
@headers
end
def csv_contents
@result
end
def each(&block)
@result.each(&block)
end
def initialize
@result = []
read
end
end
class CsvRow
def initialize(headers, data)
@headers = headers
@data = data
end
def method_missing(name, *args)
idx = @headers.index{ |header| header == name.to_s}
@data[idx]
end
end
class RubyCsv < ActsAsCsv
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