Guest User

Untitled

a guest
Jul 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.65 KB | None | 0 0
  1. module ActsAsCsv
  2. def self.included(base)
  3. base.extend ClassMethods
  4. end
  5.  
  6. module ClassMethods
  7. def acts_as_csv
  8. include InstanceMethods
  9. end
  10. end
  11.  
  12. module InstanceMethods
  13.  
  14. def read
  15. @csv_contents = []
  16. filename = self.class.to_s.downcase + '.txt'
  17. file = File.new(filename)
  18. @headers = file.gets.chomp.split(', ')
  19.  
  20. file.each do |row|
  21. @csv_contents << row.chomp.split(', ')
  22. end
  23. end
  24.  
  25. attr_accessor :headers, :csv_contents
  26.  
  27. def initialize
  28. read
  29. end
  30. end
  31. end
  32.  
  33. class RubyCsv
  34. include ActsAsCsv
  35. acts_as_csv
  36. end
  37.  
  38. m = RubyCsv.new
  39. puts m.headers.inspect # 出力:["one", "two"]
  40. puts m.csv_contents.inspect # 出力:[["lions", "tigers"]]
Add Comment
Please, Sign In to add comment