Skip to content

Commit

Permalink
Merge pull request #31 from ruby/pz-tempfile-finalizers
Browse files Browse the repository at this point in the history
Ensure finalizer order in Tempfile
  • Loading branch information
peterzhu2118 authored Aug 20, 2024
2 parents ae896a5 + eb2d8b1 commit 37bee10
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/tempfile.rb
Original file line number Diff line number Diff line change
Expand Up @@ -228,22 +228,25 @@ def initialize(basename="", tmpdir=nil, mode: 0, **options)
tmpfile = File.open(tmpname, @mode, **opts)
@opts = opts.freeze
end
ObjectSpace.define_finalizer(@finalizer_obj, Remover.new(tmpfile.path))
ObjectSpace.define_finalizer(self, Closer.new(tmpfile))

super(tmpfile)

define_finalizers
end

private def define_finalizers
ObjectSpace.define_finalizer(@finalizer_obj, Closer.new(__getobj__))
ObjectSpace.define_finalizer(@finalizer_obj, Remover.new(__getobj__.path))
end

def initialize_dup(other) # :nodoc:
initialize_copy_iv(other)
super(other)
ObjectSpace.define_finalizer(self, Closer.new(__getobj__))
end

def initialize_clone(other) # :nodoc:
initialize_copy_iv(other)
super(other)
ObjectSpace.define_finalizer(self, Closer.new(__getobj__))
end

private def initialize_copy_iv(other) # :nodoc:
Expand All @@ -256,10 +259,13 @@ def initialize_clone(other) # :nodoc:
# Opens or reopens the file with mode "r+".
def open
_close
ObjectSpace.undefine_finalizer(self)

mode = @mode & ~(File::CREAT|File::EXCL)
__setobj__(File.open(__getobj__.path, mode, **@opts))
ObjectSpace.define_finalizer(self, Closer.new(__getobj__))

ObjectSpace.undefine_finalizer(@finalizer_obj)
define_finalizers

__getobj__
end

Expand Down Expand Up @@ -327,7 +333,10 @@ def unlink
# may not be able to unlink on Windows; just ignore
return
end

ObjectSpace.undefine_finalizer(@finalizer_obj)
ObjectSpace.define_finalizer(@finalizer_obj, Closer.new(__getobj__))

@unlinked = true
end
alias delete unlink
Expand Down

0 comments on commit 37bee10

Please sign in to comment.