Created
December 31, 2012 17:01
-
-
Save brianium/4421308 to your computer and use it in GitHub Desktop.
7 weeks of 7 languages - Ruby Day 3 Metaprogramming
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
module ActsAsCsv | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def acts_as_csv | |
include InstanceMethods | |
end | |
end | |
module InstanceMethods | |
def read | |
@rows = [] | |
filename = self.class.to_s.downcase + '.txt' | |
file = File.new(filename) | |
@headers = file.gets.chomp.split(', ') | |
file.each do |row| | |
row = row.chomp.split(', ') | |
@rows << CsvRow.new(Hash[*headers.zip(row).flat_map {|i| i}]) | |
end | |
end | |
attr_accessor :headers, :rows | |
def initialize | |
read | |
end | |
def each(&block) | |
@rows.each do |c| | |
block.call c | |
end | |
end | |
end | |
class CsvRow | |
attr_accessor :values | |
def initialize(values = {}) | |
@values = values | |
end | |
def method_missing name, *args | |
@values[name.to_s] if @values.has_key?(name.to_s) | |
end | |
end | |
end | |
class FamilyCsv | |
include ActsAsCsv | |
acts_as_csv | |
end | |
csv = FamilyCsv.new | |
csv.each do |row| | |
puts row.first | |
puts row.last | |
puts row.relationship | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment