Temporary Files in Ruby

Temporary Files in Ruby

temporary files in ruby

 

Working with Ruby on Rails applications, many times such as in case of file upload services, generating/processing csv data, uploading data to external services like Amazon there is a need to create temporary files.
A very common solution is to create a usual file object and delete it later. Imagine a scenario where you had created a large data file (say a 2GB) for temporary usage and forgot to delete it.

 

The Solution… Ruby Tempfile Class

 

Tempfile is a ruby utility class for managing temporary files. The class can be used to create temporary files. The file is generated with a unique name each time and is garbage collected when it goes out of scope. This saves you the trouble to have to remove them explicitly.
Since explicitly temporary deleting files is a good idea you can still do it with Tempfile object, Tempfile#unlink .
All actions on a File object are also valid on a Tempfile object, hence no loss of functionality.

Creating a using a temporary file with Tempfile class

 

> tempfile = Tempfile.new([temp, text])
=> #<Tempfile:/tmp/temp20141109-10110-2pjq04text>
> tempfile.write(sample tempfile.)
=> 16
> tempfile.rewind
=> 0
> tempfile.read
=> sample tempfile.
> tempfile.close
=> nil
> tempfile.unlink
=> #<Tempfile:>
view rawtempfile.rb hosted with ❤ by GitHub

 

For complete documentation of class ref Ruby Tempfile

About RemotePanda

RemotePanda is a personalized platform for companies to hire remote talent and get the quality work delivered from the city Pune. The resources in our talent pool are our close network connections. While connecting them with you, we make sure to manage the quality, growth, legalities, and the delivery of their work. The idea is to make remote work successful for you. Get in touch with us to learn why RemotePanda is the best fit solution for your business requirements.

Comments are closed.