Created
November 9, 2011 19:02
-
-
Save jdoig/1352535 to your computer and use it in GitHub Desktop.
Total bastardization of day 3
This file contains hidden or 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
def get_filename(obj) | |
filename = obj.to_s.downcase + '.txt' | |
end | |
def read_line(line) | |
line.chomp.split(', ') | |
end | |
module ActsAsCsv | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def acts_as_csv | |
include InstanceMethods | |
headers = read_line(File.open(get_filename(self)).readline).each{|h| define_method(h){ @csv_contents[h]} } | |
end | |
end | |
module InstanceMethods | |
def read | |
filename = get_filename(self.class) | |
File.open(filename).each_with_index{|l,i| i == 0 ? @csv_contents = Hash[read_line(l).collect{|h| [h,[]]}] : read_line(l).each_with_index{|v,i| @csv_contents.values[i] << v}} | |
end | |
end | |
def row(row_number) | |
@csv_contents.values.collect{|c| c[row_number]} | |
end | |
attr_accessor :headers, :csv_contents | |
def initialize | |
read | |
end | |
end | |
class RubyCsv | |
include ActsAsCsv | |
acts_as_csv | |
end | |
csv = RubyCsv.new | |
csv.one.each {|row| puts row} | |
csv.two.each {|row| puts row} | |
puts csv.row(0) |
Nice that you don't have to override method_missing for this though.
Hehe; yeah this one involved a lot of me playing with Ruby rather than writing 'good' Ruby. I particularly dislike that line as it wouldn't run if I put the ternary operator over multiple lines... It would have certainly benefited from using a do-end block rather than an in-line statement.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While I love how succinct you can be with Ruby, I do wonder how long it would take somebody else to understand this line and if you maaaaaybe could have made it a bit more readable :)
File.open(filename).each_with_index{|l,i| i == 0 ? @csv_contents = Hash[read_line(l).collect{|h| [h,[]]}] : read_line(l).each_with_index{|v,i| @csv_contents.values[i] << v}}