You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.4 KiB
59 lines
1.4 KiB
5 years ago
|
require 'forwardable'
|
||
|
#---
|
||
|
# 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
|
||
|
extend Forwardable
|
||
|
include Enumerable
|
||
|
|
||
|
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 << CsvRow.new(@headers, row.chomp.split(','))
|
||
|
end
|
||
|
end
|
||
|
|
||
|
attr_accessor :headers, :csv_contents
|
||
|
def_delegators :@csv_contents, :each
|
||
|
def initialize
|
||
|
read
|
||
|
end
|
||
|
end
|
||
|
|
||
|
class CsvRow < Struct.new(:headers, :cells)
|
||
|
def method_missing(name)
|
||
|
self.cells[self.headers.index(name.to_s)]
|
||
|
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.each {|row| puts row.one}
|