Ruby Metaprogramming - Persist Tempfile

A stupid and useless example of metaprogramming in ruby :man_shrugging:

Ruby deletes temp files when a reference to Tempfile is garbage collected by 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

# We are reopening and monkey patching 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)
    FileUtils.mv(self.path, filename)
    # remove finalizer so that the temporary file will not be deleted at the exit.
    ObjectSpace.undefine_finalizer(self)
  end
end

Usage

temp_file = Tempfile.new
# do something with temp_file
temp_file.persist("/home/electron/saved_files/file.csv")

But Why?

You can and should use File when possible, I did this because:

  • I wanted to demo ruby meta programming capabilities
  • I had some code which returned Tempfile and I was too lazy to dive in and change it during my debugging session :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


👋 Like what you have read, Subscribe to get updates 📩

Continue Reading