Question

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?

Was it helpful?

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

OTHER TIPS

I'm not sure how you could write something to reliably detect when the file is closed. You might be able to keep checking something like File.mtime within a loop, so that you can tell if the modified time has changed, but it wouldn't be a good way of doing it.

I wonder why you are trying to do it this way.

If you want user input, can you not just use gets instead?

If you want to make the interface more pleasant for entering data, you would be better off using something like Ruby Shoes.

A final option which may require a little extra programming would be to effectively run Ruby as a primitive web server (and post the data to the server via an HTML form). For that, you could use something like Mongrel (gem install mongrel).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top