Created
January 8, 2014 19:40
-
-
Save mperham/8323180 to your computer and use it in GitHub Desktop.
Using tempfile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Also a good example but in my case I need to pass the file path to another API so unlink is not possible.
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
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.