Ruby Sinatra app for downloading a file (as streaming)

ruby, sinatra

Solution

get '/download' do 
    data = [{:name => "john", :age => 12, :state => 'ca'}, {:name => "tony", :age => 22, :state => 'va'}]

    content_type 'application/csv'
    attachment "myfilename.csv"
    data.each{|k, v|
       p v
    }
end

This works for me. I know it is incomplete as I have to put header and comma in the excel file with line break. But this works.

Problem

I have a sinatra app, where I want to make a download feature. This download take data from table and make excel to download for user. ``` require 'csv' get '/download' do data = [{:name => "john", :age => 12, :state => 'ca'}, {:name => "tony", :age => 22, :state => 'va'}] # I want to download this data as excel file and the content of file should be as follows: # name,age,state # john,12,ca # tony,22,va # I don't want to save data as a temp file on the server and then throw to user for download # rather I want to stream data for download on the browser. So I used this, # but it is not working send_data (data, :type => 'application/csv', :disposition => 'attachment') end ``` What am I doing wrong? Or how to achieve, what I am trying to do? I was trying to follow http://sinatra.rubyforge.org/api/classes/Sinatra/Streaming.html UPDATE: I am not married to send_data method of sinatra. If streaming blocks my server for that duration, then I am open to alternatives.

Original source