DEV Community

Cover image for Dealing with the lifecycle of a Tempfile
olistik
olistik

Posted on

3

Dealing with the lifecycle of a Tempfile

When dealing with Tempfiles in Ruby it's important to remember that when a tempfile object gets deallocated, the referenced file gets deleted as well.

require 'tempfile'

def foo
  Tempfile.new.path
end

path = foo # => "/tmp/20210723-30107-1h52x7" 

# Soon after:

File.exists?(path) # => true

# But wait for it..

File.exists?(path) # => false 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
cescquintero profile image
Francisco Quintero πŸ‡¨πŸ‡΄ β€’

Correct. Once I needed to use Tempfile because was dealing with files in docker containers. To prevent losing the file I set it up to make a copy to a designated folder so that the process could finish with no risk of losing the file.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay