Created
November 15, 2011 19:49
-
-
Save devnoo/1368106 to your computer and use it in GitHub Desktop.
ActsAsCsv
This file contains hidden or 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
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