Skip to content

Instantly share code, notes, and snippets.

@ice09
Created April 28, 2013 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ice09/5477959 to your computer and use it in GitHub Desktop.
Save ice09/5477959 to your computer and use it in GitHub Desktop.
7l7w ruby day3
# Modify the CSV application to support an each method to return a CsvRow object.
# Use method_missing on that CsvRow to return the value for the column of each heading.
#
# Kontonummer, Name
# 12144445678, ice09
class CsvRow
attr_accessor :values, :keys
def initialize( keys, values )
@keys = keys
@values = values
end
def method_missing(id, *args)
# if method is left out (ie. return all values), id == :to_ary
if (id==:to_ary)
then return @values
else return @values[@keys.index(id.to_s)]
end
end
end
module ActsAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
include Enumerable
end
end
module InstanceMethods
attr_accessor :headers, :csv_contents
def each &block
@csv_contents.each{|csvRow| block.call(csvRow)}
end
def read
@csv_contents = []
filename = self.class.to_s.downcase + '.txt'
file = File.new(filename)
@headers = file.gets.chomp.split(';').collect{|s| s.delete("\"")}
file.each do |row|
values = row.chomp.split(';').collect{|s| s.delete("\"")}
@csv_contents << CsvRow.new(@headers, values)
end
end
def initialize
read
end
end
end
class RubyCsv # no inheritance! You can mix it in
include ActsAsCsv
acts_as_csv
end
# use it
m = RubyCsv.new
m.each { |it| puts it.Kontonummer }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment