Sunday, January 18, 2009

Generating CSV output in Sinatra

To generate CSV output in Sinatra:

get '/tax/export/:financial_year_start' do
tax = TaxReport.new( params[:financial_year_start] )
headers "Content-Disposition" => "attachment;filename=tax#{tax.year_start}.csv",
"Content-Type" => "application/octet-stream"
result = ""
tax.invoices.each do |inv|
result << "#{inv.date.strftime("%d %b %y")}, #{inv.number}, #{inv.company}, #{inv.total_ex_gst}, #{inv.gst}, #{inv.total}"
end
end


Nothing particularly difficult about it, like the rest of Sinatra: it just works.

1 comment:

dbwest said...

Thanks. Useful.