From da454371fe8ee2f2dcbc522365409d4341c27b6f Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Fri, 23 Aug 2024 19:40:13 +0900 Subject: [PATCH] Support anonymous tempfile on earlier than Ruby 3.2 --- lib/tempfile.rb | 20 ++++++++++++++++++-- test/test_tempfile.rb | 12 ++---------- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/lib/tempfile.rb b/lib/tempfile.rb index 463655e..5350e1f 100644 --- a/lib/tempfile.rb +++ b/lib/tempfile.rb @@ -556,7 +556,7 @@ def open(*args, **kw) # Related: Tempfile.new. # def Tempfile.create(basename="", tmpdir=nil, mode: 0, anonymous: false, **options, &block) - if anonymous && RUBY_VERSION >= '3.2' + if anonymous create_anonymous(basename, tmpdir, mode: mode, **options, &block) else create_with_filename(basename, tmpdir, mode: mode, **options, &block) @@ -593,6 +593,20 @@ class << Tempfile end end +File.open(IO::NULL) do |f| + File.new(f.fileno, autoclose: false, path: "").path +rescue IOError + #--- + module PathAttr + attr_reader :path + + def self.set_path(file, path) + file.extend(PathAttr).instance_variable_set(:@path, path) + end + end + #+++ +end + private def create_anonymous(basename="", tmpdir=nil, mode: 0, **options, &block) tmpfile = nil tmpdir = Dir.tmpdir() if tmpdir.nil? @@ -608,12 +622,14 @@ class << Tempfile mode |= File::SHARE_DELETE | File::BINARY # Windows needs them to unlink the opened file. tmpfile = create_with_filename(basename, tmpdir, mode: mode, **options) File.unlink(tmpfile.path) + tmppath = tmpfile.path end path = File.join(tmpdir, '') - if tmpfile.path != path + unless tmppath == path # clear path. tmpfile.autoclose = false tmpfile = File.new(tmpfile.fileno, mode: File::RDWR, path: path) + PathAttr.set_path(tmpfile, path) if defined?(PathAttr) end if block begin diff --git a/test/test_tempfile.rb b/test/test_tempfile.rb index 931b512..8077cc3 100644 --- a/test/test_tempfile.rb +++ b/test/test_tempfile.rb @@ -488,11 +488,7 @@ def test_create_anonymous_removes_file Dir.mktmpdir {|d| t = Tempfile.create("", d, anonymous: true) t.close - if RUBY_VERSION >= '3.2' - assert_equal([], Dir.children(d)) - else - refute_equal([], Dir.children(d)) - end + assert_equal([], Dir.children(d)) } end @@ -500,11 +496,7 @@ def test_create_anonymous_path Dir.mktmpdir {|d| begin t = Tempfile.create("", d, anonymous: true) - if RUBY_VERSION >= '3.2' - assert_equal(File.join(d, ""), t.path) - else - refute_equal(File.join(d, ""), t.path) - end + assert_equal(File.join(d, ""), t.path) ensure t.close if t end