Skip to content

Instantly share code, notes, and snippets.

@sriki77
Created November 12, 2011 12:37
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 sriki77/1360477 to your computer and use it in GitHub Desktop.
Save sriki77/1360477 to your computer and use it in GitHub Desktop.
Ruby Day 3
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