Search code examples
rubyfileruby-1.9.2temporary-files

Working with tempfiles in Ruby


I would like to open a tempfile in user's editor ($EDITOR), let the user to write text there, and once he closes this file to use its contents somehow (e.g. inject in another file).

What would be the most appropriate method to achieve this in Ruby 1.9.2?


Solution

  • I don't think that Tempfile is even needed here. All you need to do is create a temp file, let's say in /tmp, with an unique file name, and pass it to system( with the correct editor set. Something like this:

    def editor_command
      ENV.fetch('EDITOR') { 'vi' }
    end
    
    temp_path = "/tmp/editor-#{ Process.pid }"
    
    system "#{ editor_command } #{ temp_path }"
    
    puts File.read(temp_path)
    

    The problem with Tempfile, is that it assumes that the control over the file is always within your app, but you'll want to open the file in another OS process.

    For creating the file name, you can use SecureRandom of ruby's std lib. http://rubydoc.info/stdlib/securerandom/1.9.2/SecureRandom