Skip to content

Commit da45437

Browse files
committed
Support anonymous tempfile on earlier than Ruby 3.2
1 parent cc72591 commit da45437

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

lib/tempfile.rb

Lines changed: 18 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,20 @@ 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+
#---
600+
module PathAttr
601+
attr_reader :path
602+
603+
def self.set_path(file, path)
604+
file.extend(PathAttr).instance_variable_set(:@path, path)
605+
end
606+
end
607+
#+++
608+
end
609+
596610
private def create_anonymous(basename="", tmpdir=nil, mode: 0, **options, &block)
597611
tmpfile = nil
598612
tmpdir = Dir.tmpdir() if tmpdir.nil?
@@ -608,12 +622,14 @@ class << Tempfile
608622
mode |= File::SHARE_DELETE | File::BINARY # Windows needs them to unlink the opened file.
609623
tmpfile = create_with_filename(basename, tmpdir, mode: mode, **options)
610624
File.unlink(tmpfile.path)
625+
tmppath = tmpfile.path
611626
end
612627
path = File.join(tmpdir, '')
613-
if tmpfile.path != path
628+
unless tmppath == path
614629
# clear path.
615630
tmpfile.autoclose = false
616631
tmpfile = File.new(tmpfile.fileno, mode: File::RDWR, path: path)
632+
PathAttr.set_path(tmpfile, path) if defined?(PathAttr)
617633
end
618634
if block
619635
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)