Last active
October 22, 2015 18:51
-
-
Save peteroupc/09c63ce63b82513dfc80 to your computer and use it in GitHub Desktop.
Utility class for generating CSV files
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
require 'csv' | |
class CSVBuilder | |
# Initializes the CSV builder. | |
def initialize | |
@keys=[] | |
@items=[] | |
end | |
# Ignores certain keys previously | |
# added when writing the CSV. | |
def ignore(*keysarr) | |
for k in keysarr | |
@keys.delete(k) | |
end | |
end | |
# Adds a hash of keys. +item+ is a hash | |
# of keys and values. | |
def add(item) | |
@keys|=item.keys | |
@items.push(item) | |
end | |
# Writes the data to CSV. Each column | |
# is a different key, and the columns are | |
# sorted by key name. | |
def write(file) | |
CSV.open(file,"w"){|csv| | |
[email protected] | |
csv << sortedKeys | |
for item in @items | |
tmp=[] | |
for k in sortedKeys | |
tmp.push(item[k]||"") | |
end | |
csv << tmp | |
end | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment