Created
September 26, 2012 16:12
-
-
Save codatory/3788936 to your computer and use it in GitHub Desktop.
Plain Ruby 1.9 CSV Builder
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
# c = CSVBuilder.new ['column 1 name', 'column 2 name', 'column 3 name'] | |
# rowdata.each do |r| | |
# special_column = r.boolean ? 'YES' : 'NO' | |
# c.add_row [special_column, r.name, r.date] | |
# end | |
# c.export('optional_filename.csv') | |
require 'csv' | |
require 'tempfile' | |
class CSVBuilder | |
def initialize(head) | |
if head.is_a?(Array) | |
@tempfile = Tempfile.new('csvbuilder') | |
@tempfile << CSV.generate_line(head) | |
else | |
raise 'Headers MUST be provided as an array' | |
end | |
end | |
def add_row(row) | |
if row.is_a?(Array) | |
@tempfile << CSV.generate_line(row) | |
else | |
raise 'Row MUST be provided as an array' | |
end | |
end | |
def export(filename='export.csv') | |
@tempfile.sync | |
@tempfile.close | |
File.rename(@tempfile.path, filename) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment