Module: TmpFile

Defined in:
lib/tmp_file.rb,
lib/tmp_file/version.rb

Overview

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

Constant Summary collapse

VERSION =
'0.0.1'

Class Method Summary collapse

Class Method Details

.open(data, mime_type) {|File| ... } ⇒ Object

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.

Examples

TmpFile.open("\x89PNG\r\n\x1A[...]", 'image/png') do |tmp_file|
  # do something with tmp_file
end

Examples:

Yield a temporary PNG file with the .png extension

Parameters:

  • data (String)

    Data to store in the temporary file

  • mime_type (String)

    MIME type of the temporary file

Yields:

  • (File)

    handle of an open read-only file with the given data



21
22
23
24
25
26
27
# 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