We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
Tempfile is used for managing temporary files in Ruby. A Tempfile object creates a temporary file with a unique filename. It behaves just like a File object, and therefore we can perform all the usual file operations on it.
These days it is common
to store file on services like S3.
Let's say that we have a
file on S3.
Working with this file remotely is
In such cases it is desirable
to download the file on local machine
After the work is done then
file should be deleted.
Tempfile is ideal for such cases.
If we want to create a temporary file then we needed to pass parameter to it prior to Ruby 2.3.
1 2require 'tempfile' 3file = Tempfile.new('bigbinary') 4#=> #<Tempfile:/var/folders/jv/fxkfk9_10nb_964rvrszs2540000gn/T/bigbinary-20170304-10828-1w02mqi> 5
As we can see above the generated file name begins with "bigbinary" word.
Since Tempfile ensures that the generate filename will always be unique the point of passing the argument is meaningless. Ruby doc calls this passing "basename".
So in Ruby 2.3.0 it was
that the basename parameter
was meaningless for
and an empty string
will be the default value.
1 2require 'tempfile' 3file = Tempfile.new 4#=> #<Tempfile:/var/folders/jv/fxkfk9_10nb_964rvrszs2540000gn/T/20170304-10828-1v855bf> 5
But the same was not implemented for
1 2# Ruby 2.3.0 3require 'tempfile' 4Tempfile.create do |f| 5 f.write "hello" 6end 7 8ArgumentError: wrong number of arguments (given 0, expected 1..2) 9
in Ruby 2.4.
So now the basename parameter
is set to
empty string by default,
to keep it
consistent with the
1 2# Ruby 2.4 3require 'tempfile' 4Tempfile.create do |f| 5 f.write "hello" 6end 7=> 5 8