class Rack::Test::UploadedFile
post “/photos”, “file” => Rack::Test::UploadedFile.new(“me.jpg”, “image/jpeg”)
Example:
in the params causes Rack::Test to build and issue a multipart request.
Wraps a Tempfile with a content type. Including one or more UploadedFile’s
def self.actually_finalize(file)
Close and unlink the given file, used as a finalizer for the tempfile,
def self.actually_finalize(file) file.close file.unlink end
def self.finalize(file)
def self.finalize(file) proc { actually_finalize file } end
def append_to(buffer)
after to make sure all data in tempfile is appended to the
copies of file data in memory. Rewind tempfile before and
Append to given buffer in 64K chunks to avoid multiple large
def append_to(buffer) tempfile.rewind buf = String.new buffer << tempfile.readpartial(65_536, buf) until tempfile.eof? tempfile.rewind nil end
def initialize(content, content_type = 'text/plain', binary = false, original_filename: nil)
binary :: Whether the file should be set to binmode (content treated as binary).
content_type :: MIME type of the file
content :: is a path to a file, or an {IO} or {StringIO} object representing the content.
Arguments:
Creates a new UploadedFile instance.
def initialize(content, content_type = 'text/plain', binary = false, original_filename: nil) @content_type = content_type @original_filename = original_filename case content when StringIO initialize_from_stringio(content) else initialize_from_file_path(content) end @tempfile.binmode if binary end
def initialize_from_file_path(path)
Create a tempfile and copy the content from the given path into the tempfile, optionally renaming if
def initialize_from_file_path(path) raise "#{path} file does not exist" unless ::File.exist?(path) @original_filename ||= ::File.basename(path) extension = ::File.extname(@original_filename) @tempfile = Tempfile.new([::File.basename(@original_filename, extension), extension]) @tempfile.set_encoding(Encoding::BINARY) ObjectSpace.define_finalizer(self, self.class.finalize(@tempfile)) FileUtils.copy_file(path, @tempfile.path) end
def initialize_from_stringio(stringio)
def initialize_from_stringio(stringio) raise(ArgumentError, 'Missing `original_filename` for StringIO object') unless @original_filename @tempfile = stringio end
def method_missing(method_name, *args, &block)
def method_missing(method_name, *args, &block) tempfile.public_send(method_name, *args, &block) end
def path
def path tempfile.path end
def respond_to_missing?(method_name, include_private = false) #:nodoc:
def respond_to_missing?(method_name, include_private = false) #:nodoc: tempfile.respond_to?(method_name, include_private) || super end