Skip to content

Commit 136cbf0

Browse files
nobumatzbot
authored andcommitted
[ruby/tempfile] Support anonymous tempfile on earlier than Ruby 3.2
ruby/tempfile@7052805029
1 parent 2e07c13 commit 136cbf0

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

lib/tempfile.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ def open(*args, **kw)
556556
# Related: Tempfile.new.
557557
#
558558
def Tempfile.create(basename="", tmpdir=nil, mode: 0, anonymous: false, **options, &block)
559-
if anonymous && RUBY_VERSION >= '3.2'
559+
if anonymous
560560
create_anonymous(basename, tmpdir, mode: mode, **options, &block)
561561
else
562562
create_with_filename(basename, tmpdir, mode: mode, **options, &block)
@@ -593,6 +593,18 @@ class << Tempfile
593593
end
594594
end
595595

596+
File.open(IO::NULL) do |f|
597+
File.new(f.fileno, autoclose: false, path: "").path
598+
rescue IOError
599+
module PathAttr # :nodoc:
600+
attr_reader :path
601+
602+
def self.set_path(file, path)
603+
file.extend(self).instance_variable_set(:@path, path)
604+
end
605+
end
606+
end
607+
596608
private def create_anonymous(basename="", tmpdir=nil, mode: 0, **options, &block)
597609
tmpfile = nil
598610
tmpdir = Dir.tmpdir() if tmpdir.nil?
@@ -608,12 +620,14 @@ class << Tempfile
608620
mode |= File::SHARE_DELETE | File::BINARY # Windows needs them to unlink the opened file.
609621
tmpfile = create_with_filename(basename, tmpdir, mode: mode, **options)
610622
File.unlink(tmpfile.path)
623+
tmppath = tmpfile.path
611624
end
612625
path = File.join(tmpdir, '')
613-
if tmpfile.path != path
626+
unless tmppath == path
614627
# clear path.
615628
tmpfile.autoclose = false
616629
tmpfile = File.new(tmpfile.fileno, mode: File::RDWR, path: path)
630+
PathAttr.set_path(tmpfile, path) if defined?(PathAttr)
617631
end
618632
if block
619633
begin

test/test_tempfile.rb

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -488,23 +488,15 @@ def test_create_anonymous_removes_file
488488
Dir.mktmpdir {|d|
489489
t = Tempfile.create("", d, anonymous: true)
490490
t.close
491-
if RUBY_VERSION >= '3.2'
492-
assert_equal([], Dir.children(d))
493-
else
494-
refute_equal([], Dir.children(d))
495-
end
491+
assert_equal([], Dir.children(d))
496492
}
497493
end
498494

499495
def test_create_anonymous_path
500496
Dir.mktmpdir {|d|
501497
begin
502498
t = Tempfile.create("", d, anonymous: true)
503-
if RUBY_VERSION >= '3.2'
504-
assert_equal(File.join(d, ""), t.path)
505-
else
506-
refute_equal(File.join(d, ""), t.path)
507-
end
499+
assert_equal(File.join(d, ""), t.path)
508500
ensure
509501
t.close if t
510502
end

0 commit comments

Comments
 (0)