0

i'm using rails 3.2.22 and ruby 2.2.

i'm creating a text file and i want to send that for download using send_to. My code works as expected but every time i hit the action one local copy of the file is getting created in my application root folder. I dont want this and file should directly go to download folder. Am i doing anything wrong ??

def save_trunk_logs
    data = ""
    file = "test.txt"
    trunk_logs = some data
    File.open(file, "w") do |aFile|
      aFile.write("Trunk Name : #{trunk_name}\n")
      aFile.write("*"*100)
      aFile.write("\n")
      aFile.write("Time Stamp"+"\t"+"Log Message\n")
      trunk_logs.each do |msg|
      text =format_log_messages msg
        data << "#{data}\n"
     end
  end
  send_file file, :type => 'application/text; charset=UTF-8', :disposition => 'attachment'
end

Any help is appreciated.

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
Ajith
  • 325
  • 4
  • 17
  • 1
    You need to delete the file after you've sent it. You probably also want to look into `Tempfile` instead, which is better suited for temporary file creation. Look here for more information: http://stackoverflow.com/questions/18232088/in-ruby-on-rails-after-send-file-method-delete-the-file-from-server – Casper Oct 31 '16 at 04:18
  • 1
    either as casper says or do a check so you don't recreate it, i.e. `if File.exists?(file) ... File.open ...` – max pleaner Oct 31 '16 at 05:11

1 Answers1

0

Try this.

  def save_trunk_logs
    data = ""
    io = StringIO.new
    trunk_logs = some data
    io.write("Trunk Name : #{trunk_name}\n")
    io.write("*"*100)
    io.write("\n")
    io.write("Time Stamp"+"\t"+"Log Message\n")
    trunk_logs.each do |msg|
      text =format_log_messages msg
      data << "#{data}\n"
    end
    send_data io.string, :type => 'application/text; charset=UTF-8', :disposition => 'attachment'
  end
J Edward Ellis
  • 1,368
  • 2
  • 12
  • 21