Class: Kronk::Multipart

Inherits:
Object
  • Object
show all
Defined in:
lib/kronk/multipart.rb

Overview

Builder for the body of a multipart request.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(boundary) ⇒ Multipart

Returns a new instance of Multipart.



15
16
17
18
# File 'lib/kronk/multipart.rb', line 15

def initialize boundary
  @boundary = boundary
  @parts    = []
end

Instance Attribute Details

#boundaryObject (readonly)

The separator used between parts.



12
13
14
# File 'lib/kronk/multipart.rb', line 12

def boundary
  @boundary
end

#partsObject (readonly)

An array of parts for the multipart body.



9
10
11
# File 'lib/kronk/multipart.rb', line 9

def parts
  @parts
end

Instance Method Details

#add(name, value, headers = nil) ⇒ Object

Add a new part to the body.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/kronk/multipart.rb', line 24

def add name, value, headers=nil
  headers ||= {}

  headers['content-disposition'] = "form-data; name=\"#{name}\""

  if value.respond_to?(:path)
    headers['content-disposition'] <<
      "; filename=\"#{File.basename value.path}\""

    headers['Content-Type'] ||= MIME::Types.of(value.path)[0]
    headers['Content-Type'] &&= headers['Content-Type'].to_s
  end

  if value.respond_to?(:read)
    headers['Content-Type']              ||= "application/octet-stream"
    headers['Content-Transfer-Encoding'] ||= 'binary'
  end

  parts << [headers, value]
end

#to_ioObject

Convert the instance into a MultipartIO instance.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/kronk/multipart.rb', line 49

def to_io
  io   = Kronk::MultipartIO.new
  buff = ""

  parts.each do |(headers, value)|
    buff << "--#{@boundary}\r\n"
    buff << "content-disposition: #{headers['content-disposition']}\r\n"

    headers.each do |hname, hvalue|
      next if hname == 'content-disposition'
      hvalue = hvalue.to_s.inspect if hvalue.to_s.index ":"
      buff << "#{hname}: #{hvalue}\r\n"
    end

    buff << "\r\n"

    if value.respond_to?(:read)
      io.add buff.dup
      io.add value
      buff.replace ""
    else
      buff << value.to_s
    end

    buff << "\r\n"
  end

  buff << "--#{@boundary}--"
  io.add buff

  io
end