views:

678

answers:

2

My rails application runs on a Ubuntu server machine.

I need to create temporary files in order to "feed" them to a second, independent app (I'll be using rake tasks for this, in case this information is needed)

My question is: what is the best way of creating temporary fields on a rails application?

Since I'm in ubuntu, I could create them on /tmp/whatever, but what would work only in linux.

I'd like my application to be as portable as possible - so it can be installed on Windows machines & mac, if needed.

Any ideas?

Thanks a lot.

+5  A: 

Rails apps also have their own tmp/ directory. I guess that one is always available and thus a good candidate to use and keep your application portable.

Veger
+5  A: 

tmp/ is definitively the right place to put the files.

The best way I've found of creating files on that folder is using ruby's tempfile library.

The code looks like this:

require 'tempfile'

def foo()
  # creates a temporary file in tmp/
  temp_file = Tempfile.new('prefix', "#{Rails.root}/tmp")
  temp_file.print('a temp message')
  temp_file.flush

  #... do stuff with the temp file
end

I like this solution because:

  • It generates random file names automatically (you can provide a prefix)
  • It automatically deletes the files when they are no longer used. For example, if invoked on a rake task, the files are removed when the rake task ends.
egarcia