Created
May 14, 2013 17:54
-
-
Save sleepyfox/5578023 to your computer and use it in GitHub Desktop.
Ruby day 3 code
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
rubycsv.txt | |
=== | |
first, last, country | |
Yukihiro, Matsumoto, Japan | |
Bruce, Tate, USA | |
animals.txt | |
=== | |
one, two | |
lions, tigers | |
bears, giraffes | |
acts_as_csv_module.rb | |
=== | |
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 | |
end | |
end | |
class RubyCsv # no inheritance! You can mix it in | |
include ActsAsCsv | |
acts_as_csv | |
end | |
m = RubyCsv.new | |
puts m.headers.inspect | |
puts m.csv_contents.inspect | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment