What is the difference between send_data and send_file in Ruby on Rails?

Mr. Black picture Mr. Black · Apr 4, 2011 · Viewed 62.7k times · Source

Which one is best for streaming and file downloads?

Please provide examples.

Answer

fl00r picture fl00r · Apr 4, 2011
send_data(_data_, options = {})
send_file(_path_, options = {}) 

Main difference here is that you pass DATA (binary code or whatever) with send_data or file PATH with send_file.

So you can generate some data and send it as an inline text or as an attachment without generating file on your server via send_data. Or you can send ready file with send_file

data = "Hello World!"
send_data( data, :filename => "my_file.txt" )

Or

data = "Hello World!"
file = "my_file.txt"
File.open(file, "w"){ |f| f << data }
send_file( file )

For perfomance it is better to generate file once and then send it as many times as you want. So send_file will fit better.

For streaming, as far as I understand, both of this methods use the same bunch of options and settings, so you can use X-Send or whatever.

UPD

send_data and save file:

data = "Hello World!"
file = "my_file.txt"
File.open(file, "w"){ |f| f << data }
send_data( data )