Skip to content

Instantly share code, notes, and snippets.

@mperham
Created January 8, 2014 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mperham/8323180 to your computer and use it in GitHub Desktop.
Save mperham/8323180 to your computer and use it in GitHub Desktop.
Using tempfile
# Use open to ensure tempfile is cleaned up asap
Tempfile.open("somename") do |tfile|
# Stage 1 - create the tempfile with some data
tfile.write "some bytes"
tfile.close
# Stage 2 - use the tempfile
File.open(tfile.path) do |file|
assert "some bytes", file.read
end
end
@nyarly
Copy link

nyarly commented Jan 8, 2014

Try out: Tempfile.open("foo"){|tf| tf.unlink; tf.puts "Thing"; tf.rewind; p tf.read}

For small amounts of data, StringIO may be preferrable.

@mperham
Copy link
Author

mperham commented Jan 8, 2014

Also a good example but in my case I need to pass the file path to another API so unlink is not possible.

@mperham
Copy link
Author

mperham commented Jan 8, 2014

Ah, BEWARE: Tempfile.open just delegates to File.open so you don't actually get a tempfile with a randomly generated name. Ruby 2.1 has a nice Tempfile.create method but 2.0 doesn't support anything beyond Tempfile.new.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment