Created
October 6, 2013 13:50
-
-
Save reuk/6854373 to your computer and use it in GitHub Desktop.
I've been learning ruby. I liked it more than I thought I would.
This file contains 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
#!/usr/bin/env ruby | |
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 | |
def each(&block) | |
@csv_contents.each do |item| | |
yield(CsvRow.new(@headers, item)) | |
end | |
end | |
end | |
class CsvRow | |
def initialize(head, content) | |
@contents = Hash[head.zip(content)] | |
end | |
def method_missing name, *args | |
@contents[name.to_s] | |
end | |
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