'How to add extension to ruby Tempfile object?

How to add extension for Tempfile object?

image_path = "https://api.tinify.com/output/g85retpckb5fz2x8zpjrvtj0jcv1txm0"
image = open(image_path)
image.path # "/tmp/open-uri20191225-21585-oo95rb"

Now I want to make this file has jpg extension how can I do that?

I have also tried to convert it to File class but couldn't change extension too.

new_image = File.new(image)
new_image.path # "/tmp/open-uri20191225-21585-oo95rb"


Solution 1:[1]

Use FileUtils#mv to physically move the file over the filesystem.

image_path = "https://api.tinify.com/output/g85retpckb5fz2x8zpjrvtj0jcv1txm0"
image = open(image_path)
image.path # "/tmp/open-uri20191225-21585-oo95rb"

image_path_jpg = "#{image.path}.jpg"
FileUtils.mv(image.path, image_path_jpg)
image = open(image_path_jpg)
image.path # "/tmp/open-uri20191225-21585-oo95rb.jpg"

Please note that you are responsible for file deletion now, since the file is not a temp file anymore.

Solution 2:[2]

If you're creating the Tempfile yourself you can do

>> Tempfile.new([ 'foobar', '.xlsx' ]).path
=> "/tmp/foobar20130115-19153-1xhbncb-0.xlsx"

Solution 3:[3]

Modifying the tempfile module

To add extension to a Ruby tempfile, I figured that tempfile module needs to be modified a little.

Make a class like this:

require 'tempfile'

class CustomTempfle < Tempfile
  def initialize(filename, temp_dir = nil)
    temp_dir ||= Dir.tmpdir
    extension = File.extname(filename)
    basename = File.basename(filename, extension)
    super([basename, extension], temp_dir)
  end
end

And then you can call the class and provide the filename with the extensio and write to the file like so.

CustomTempfle.open('filename.pdf', nil) do |tmp|
  File.open(tmp, 'wb') { |f| f << 'content_of_the_file' }
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmed Salah
Solution 2
Solution 3 Nima Yonten