Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support anonymous tempfile on earlier than Ruby 3.2 #36

Merged
merged 1 commit into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions lib/tempfile.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -593,6 +593,18 @@ class << Tempfile
end
end

File.open(IO::NULL) do |f|
File.new(f.fileno, autoclose: false, path: "").path
rescue IOError
module PathAttr # :nodoc:
attr_reader :path

def self.set_path(file, path)
file.extend(self).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?
Expand All @@ -608,12 +620,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
Expand Down
12 changes: 2 additions & 10 deletions test/test_tempfile.rb
Original file line number Diff line number Diff line change
Expand Up @@ -488,23 +488,15 @@ 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

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
Expand Down