# HG changeset patch # User IBBoard # Date 1484945941 0 # Node ID cd874e58dbc5958280e6e398d99557c96663dafb # Parent 720e9201dd98b99de1a0b0f79368c638d1cec215 Add code from book diff -r 720e9201dd98 -r cd874e58dbc5 1-Ruby/acts_as_csv_module.rb --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/1-Ruby/acts_as_csv_module.rb Fri Jan 20 20:59:01 2017 +0000 @@ -0,0 +1,47 @@ +#--- +# Excerpted from "Seven Languages in Seven Weeks", +# published by The Pragmatic Bookshelf. +# Copyrights apply to this code. It may not be used to create training material, +# courses, books, articles, and the like. Contact us if you are in doubt. +# We make no guarantees that this code is fit for any purpose. +# Visit http://www.pragmaticprogrammer.com/titles/btlang for more book information. +#--- +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 +