Class: Protocol::Multipart::IOPart

Inherits:
Part
  • Object
show all
Extended by:
Escape
Defined in:
lib/protocol/multipart/io_part.rb

Overview

A part that contains IO content (files, streams, etc.).

Instance Attribute Summary collapse

Attributes inherited from Part

#headers

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Escape

escape_field_name, unescape_field_name

Methods inherited from Part

#The headers as name/value pairs.=

Constructor Details

#initialize(headers, io) ⇒ IOPart

Initialize a new IOPart with the given headers and IO object.



39
40
41
42
# File 'lib/protocol/multipart/io_part.rb', line 39

def initialize(headers, io)
  super(headers)
  @io = io
end

Instance Attribute Details

#ioObject (readonly)

The underlying IO object.



46
47
48
# File 'lib/protocol/multipart/io_part.rb', line 46

def io
  @io
end

Class Method Details

.open(path, mime_type: nil, name: nil, headers: {}) ⇒ Object

Opens a file and creates an IOPart for it.



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/protocol/multipart/io_part.rb', line 22

def self.open(path, mime_type: nil, name: nil, headers: {})
  io = File.open(path, "rb")
  
  name ||= File.basename(path)
  
  headers = headers.merge(
    "content-disposition" => "attachment; filename=\"#{escape_field_name name}\"",
    "content-type" => mime_type || "application/octet-stream"
  )
  
  return new(headers, io)
end

Instance Method Details

#call(writable, boundary) ⇒ Object

Write the part’s content to the provided writable stream.



52
53
54
55
56
57
# File 'lib/protocol/multipart/io_part.rb', line 52

def call(writable, boundary)
  while chunk = @io.read(8192)
    break if chunk.empty?
    writable.write(chunk)
  end
end

#The IO object containing the part's data.=(IOobjectcontainingthepart's data. = (value)) ⇒ Object

The underlying IO object.



46
# File 'lib/protocol/multipart/io_part.rb', line 46

attr_reader :io