Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module ActsAsCsv
- #where should this go?
- def self.method_missing name, *args
- i = @headers.index(name)
- return if i.nil?
- @csv_contents.each do |c|
- puts c[i]
- end
- end
- def self.included(base)
- base.extend ClassMethods
- end
- def self.method_missing name, *args
- i = @headers.index(name)
- return if i.nil?
- @csv_contents.each do |c|
- puts c[i]
- end
- 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
- m.one
- # OUTPUT:
- #["one", "two"]
- #[["1correct", "1wrong"], ["2correct", "2wrong"], ["3correct", "3wrong"], ["4correct", "4wrong"], ["5correct", "5wrong"]]
- #./grep.rb:93: undefined method `one' for #<RubyCsv:0x3fd3e18> (NoMethodError)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement