Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.23 KB | None | 0 0
  1. module ActsAsCsv
  2.     #where should this go?
  3.     def self.method_missing name, *args
  4.         i = @headers.index(name)
  5.        
  6.         return if i.nil?
  7.        
  8.         @csv_contents.each do |c|
  9.             puts c[i]
  10.         end
  11.     end
  12.    
  13.     def self.included(base)
  14.         base.extend ClassMethods
  15.     end
  16.    
  17.     def self.method_missing name, *args
  18.         i = @headers.index(name)
  19.        
  20.         return if i.nil?
  21.        
  22.         @csv_contents.each do |c|
  23.             puts c[i]
  24.         end
  25.     end
  26.    
  27.     module ClassMethods
  28.         def acts_as_csv
  29.             include InstanceMethods
  30.         end
  31.     end
  32.    
  33.     module InstanceMethods
  34.         def read
  35.             @csv_contents = []
  36.             filename = self.class.to_s.downcase + '.txt'
  37.             file = File.new(filename)
  38.             @headers = file.gets.chomp.split(', ')
  39.             file.each do |row|
  40.                 @csv_contents << row.chomp.split(', ')
  41.             end
  42.         end
  43.    
  44.         attr_accessor :headers, :csv_contents
  45.        
  46.         def initialize
  47.             read
  48.         end    
  49.     end
  50. end
  51.  
  52. class RubyCsv # no inheritance! You can mix it in
  53.     include ActsAsCsv
  54.     acts_as_csv
  55. end
  56.  
  57. m = RubyCsv.new
  58. puts m.headers.inspect
  59. puts m.csv_contents.inspect
  60. m.one
  61.  
  62. # OUTPUT:
  63. #["one", "two"]
  64. #[["1correct", "1wrong"], ["2correct", "2wrong"], ["3correct", "3wrong"], ["4correct", "4wrong"], ["5correct", "5wrong"]]
  65. #./grep.rb:93: undefined method `one' for #<RubyCsv:0x3fd3e18> (NoMethodError)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement