Skip to content

Instantly share code, notes, and snippets.

@sleepyfox
Created May 14, 2013 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sleepyfox/5578023 to your computer and use it in GitHub Desktop.
Save sleepyfox/5578023 to your computer and use it in GitHub Desktop.
Ruby day 3 code
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