如何向 ruby Tempfile 对象添加扩展名?

How to add extension to ruby Tempfile object?

如何为 Tempfile 对象添加扩展名?

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

现在我想让这个文件有 jpg 扩展名,我该怎么做?

我也试过将其转换为 File class 但无法更改扩展名。

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

使用 FileUtils#mv 在文件系统中物理移动文件。

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"

请注意,您现在负责删除文件,因为该文件不再是临时文件。

如果您自己创建临时文件 you can do

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

修改临时文件模块

要向 Ruby 临时文件添加扩展,我认为 tempfile 模块需要稍微修改一下。

像这样制作class:

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

然后你可以调用 class 并为 filename 提供扩展名并像这样写入文件。

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