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.
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 decided that the basename parameter was meaningless for Tempfile#new 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 Tempfile#create.
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
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.
1 2# Ruby 2.4 3require 'tempfile' 4Tempfile.create do |f| 5 f.write "hello" 6end 7=> 5 8