Created
November 12, 2011 12:37
-
-
Save sriki77/1360477 to your computer and use it in GitHub Desktop.
Ruby Day 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActsAsCsv | |
def self.included(base) | |
base.extend ClassMethods | |
base.act_as_csv | |
end | |
module ClassMethods | |
def act_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 | |
CsvRow.headers @headers; | |
end | |
attr_accessor :headers, :csv_contents | |
def initialize | |
read | |
end | |
def each | |
@csv_contents.each {|row| yield CsvRow.new(row)} | |
end | |
end | |
end | |
class RubyCsv | |
include ActsAsCsv | |
end | |
class CsvRow | |
def initialize(row=[]) | |
@row=row | |
@headerValues=Hash.new | |
@row.each.with_index{|v,i| @headerValues[@@headers[i]]=v} | |
end | |
def method_missing(name,*args,&block) | |
@headerValues[name] | |
end | |
def self.headers(headers=[]) | |
@@headers=headers.collect{|v|v.to_sym} | |
end | |
end | |
m=RubyCsv.new.each {|row| print row.Name,"=>",row.Price; puts } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment