Persist Tempfile in Ruby

Ruby deletes temp files when a reference to Tempfile is garbage collected by using finalizer. We can reopen and patch Tempfile class and add persist method which will move Tempfile and unregister the finalizer which is responsible for cleanup

# monkey patch the Tempfile class to add a persist method.
# This method takes a filename where the temporary file will be moved to
class Tempfile
  def persist(filename), filename)
    # remove finalizer so that the temporary file will not be deleted at the exit.


temp_file =
# do something with temp_file

Buy Why?

You can and should use File when possible. I did this because I had some code which returned Tempfile and I was too lazy to dive in and change it :shipit:

Closing Note

I recommend everyone to watch Dave Thomas’s talk on Ruby MetaProgramming, MetaProgramming - Extending Ruby for Fun and Profit. It goes in details about Ruby’s open classes and how it facilitates Metaprogramming