Module: UploadIO

Defined in:
lib/composite_io.rb

Overview

Convenience methods for dealing with files and IO that are to be uploaded.

Class Method Summary collapse

Class Method Details

.convert!(io, content_type, original_filename, local_path) ⇒ Object

Enhance an existing IO for including in the params hash of a Net::HTTP::Post::Multipart by adding #content_type, #original_filename, and #local_path methods to the object’s singleton class.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/composite_io.rb', line 75

def self.convert!(io, content_type, original_filename, local_path)
  io.instance_eval(<<-EOS, __FILE__, __LINE__)
    def content_type
      "#{content_type}"
    end
    def original_filename
      "#{original_filename}"
    end
    def local_path
      "#{local_path}"
    end
  EOS
  io
end

.new(filename_or_io, content_type, filename = nil) ⇒ Object

Create an upload IO suitable for including in the params hash of a Net::HTTP::Post::Multipart.

Can take two forms. The first accepts a filename and content type, and opens the file for reading (to be closed by finalizer). The second accepts an already-open IO, but also requires a third argument, the filename from which it was opened.

UploadIO.new("file.txt", "text/plain")
UploadIO.new(file_io, "text/plain", "file.txt")


62
63
64
65
66
67
68
69
70
# File 'lib/composite_io.rb', line 62

def self.new(filename_or_io, content_type, filename = nil)
  io = filename_or_io
  unless io.respond_to? :read
    io = File.open(filename_or_io)
    filename = filename_or_io
  end
  convert!(io, content_type, File.basename(filename), filename)
  io
end