Skip to content

Instantly share code, notes, and snippets.

@peteroupc
Last active October 22, 2015 18:51
Show Gist options
  • Save peteroupc/09c63ce63b82513dfc80 to your computer and use it in GitHub Desktop.
Save peteroupc/09c63ce63b82513dfc80 to your computer and use it in GitHub Desktop.
Utility class for generating CSV files
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