summaryrefslogtreecommitdiff
path: root/ruby/csv.rb
blob: c48a11a2107ae53f3ba7043cacc674e219aa3538 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env ruby


module Csv
	class CsvRow
		def initialize keys, values
			@content = Hash[]
			keys.each do |k|
				@content[k] = values[keys.index(k)]
			end
		end

		def method_missing name, *args
			@content[name.to_s]
		end
	end

	def self.included(base)
		base.extend ClassMethods
	end

	module ClassMethods
		def acts_as_csv
			include InstanceMethods
		end
	end

	module InstanceMethods
		attr_accessor :headers, :csv_contents

		def initialize
			read
		end

		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

		def each
			@csv_contents.each {|line| yield CsvRow.new(@headers, line)}
		end
	end
end

class MyCsv
	include Csv
	acts_as_csv
end

csv = MyCsv.new
csv.each {|row| puts row.one}
puts
csv.each {|row| puts row.two}
puts
csv.each {|row| puts row.three}