module TmpFile

Provides a method to store data in a temporary file and access that file

Constants

VERSION

Public Class Methods

open(data, mime_type) { |file| ... } click to toggle source

Stores data in a temporary file and yields the file. The file is destroyed after the yielded block ends. The extension of the temporary file matches the passed mime_type.

@param [String] data Data to store in the temporary file @param [String] mime_type MIME type of the temporary file @yield [File] handle of an open read-only file with the given data

@example Yield a temporary PNG file with the .png extension

Examples

TmpFile.open("\x89PNG\r\n\x1A[...]", 'image/png') do |tmp_file|
  # do something with tmp_file
end
# File lib/tmp_file.rb, line 21
def self.open(data, mime_type)
  path = self.unique_path_for_temporary_file mime_type
  File.open(path, 'wb') {|file| file.write data}
  File.open(path, 'rb') {|file| yield file}
ensure
  FileUtils.rm_f path
end

Private Class Methods

unique_path_for_temporary_file(mime_type) click to toggle source

Returns a unique temporary path to store a file of the given mime_type.

@param [String] mime_type MIME type of the temporary file @return [String] local path that can be opened for writing

@example Find a unique path to store a temporary PNG file

TmpFile.unique_path_for_temporary_file('image/png')

# => '/var/folders/zs/xtcy1d/T/517bf6608c1314441285d4797ebcb3c2.png'
# File lib/tmp_file.rb, line 40
def self.unique_path_for_temporary_file(mime_type)
  extension = case mime_type
    when 'image/jpg'  then '.jpg'
    when 'image/jpeg' then '.jpg'
    when 'image/png'  then '.png'
    when 'image/gif'  then '.gif'
    else '.unknown'
  end
  File.join Dir.tmpdir, (SecureRandom.hex + extension)
end