Skip to content

Instantly share code, notes, and snippets.

@veloper
Forked from codatory/csv_builder.rb
Created September 20, 2012 17:21
Show Gist options
  • Save veloper/3757176 to your computer and use it in GitHub Desktop.
Save veloper/3757176 to your computer and use it in GitHub Desktop.
# 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')
class CSVBuilder
def initialize(head)
if head.is_a?(Array)
@tempfile = Tempfile.new('csvbuilder', Rails.root.join('tmp'))
@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.fsync
@tempfile.close
@tempfile.rewind(@tempfile.path, Rails.root.join(filename))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment