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.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/composite_io.rb', line 80

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

.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
71
72
73
74
75
# File 'lib/composite_io.rb', line 62

def self.new(filename_or_io, content_type, filename = nil)
  io = filename_or_io
  local_path = ""
  if io.respond_to? :read
    local_path = filename_or_io.path
  else
    io = File.open(filename_or_io)
    local_path = filename_or_io
  end
  filename ||= local_path

  convert!(io, content_type, File.basename(filename), local_path)
  io
end