This blog is part of our Ruby 2.4 series.

Tempfile class

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.

Why Tempfile when we can use File

These days it is common to store file on services like S3. Let’s say that we have a users.csv file on S3. Working with this file remotely is problematic. In such cases it is desirable to download the file on local machine for manipulation. After the work is done then file should be deleted. Tempfile is ideal for such cases.

Basename for tempfile

If we want to create a temporary file then we needed to pass parameter to it prior to Ruby 2.3.

require 'tempfile'
file = Tempfile.new('bigbinary')
#=> #<Tempfile:/var/folders/jv/fxkfk9_10nb_964rvrszs2540000gn/T/bigbinary-20170304-10828-1w02mqi>

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 decided that the basename parameter was meaningless for Tempfile#new and an empty string will be the default value.

require 'tempfile'
file = Tempfile.new
#=> #<Tempfile:/var/folders/jv/fxkfk9_10nb_964rvrszs2540000gn/T/20170304-10828-1v855bf>

But the same was not implemented for Tempfile#create.

# Ruby 2.3.0
require 'tempfile'
Tempfile.create do |f|
  f.write "hello"
end

ArgumentError: wrong number of arguments (given 0, expected 1..2)

This was fixed in Ruby 2.4. So now the basename parameter for Tempfile.create is set to empty string by default, to keep it consistent with the Tempfile#new method.

# Ruby 2.4
require 'tempfile'
Tempfile.create do |f|
  f.write "hello"
end
=> 5