Class: Rack::TestApp::MultipartBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/test_app.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(boundary = nil) ⇒ MultipartBuilder

Returns a new instance of MultipartBuilder.



124
125
126
127
128
# File 'lib/rack/test_app.rb', line 124

def initialize(boundary=nil)
  #; [!ajfgl] sets random string as boundary when boundary is nil.
  @boundary = boundary || Util.randstr_b64()
  @params = []
end

Instance Attribute Details

#boundaryObject (readonly)

Returns the value of attribute boundary.



130
131
132
# File 'lib/rack/test_app.rb', line 130

def boundary
  @boundary
end

Instance Method Details

#add(name, value, filename = nil, content_type = nil) ⇒ Object



132
133
134
135
136
137
# File 'lib/rack/test_app.rb', line 132

def add(name, value, filename=nil, content_type=nil)
  #; [!tp4bk] detects content type from filename when filename is not nil.
  content_type ||= Util.guess_content_type(filename) if filename
  @params << [name, value, filename, content_type]
  self
end

#add_file(name, file, content_type = nil) ⇒ Object



139
140
141
142
143
144
145
146
147
# File 'lib/rack/test_app.rb', line 139

def add_file(name, file, content_type=nil)
  #; [!uafqa] detects content type from filename when content type is not provided.
  content_type ||= Util.guess_content_type(file.path)
  #; [!b5811] reads file content and adds it as param value.
  add(name, file.read(), ::File.basename(file.path), content_type)
  #; [!36bsu] closes opened file automatically.
  file.close()
  self
end

#to_sObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/rack/test_app.rb', line 149

def to_s
  #; [!61gc4] returns multipart form string.
  boundary = @boundary
  s = "".force_encoding('ASCII-8BIT')
  @params.each do |name, value, filename, content_type|
    s <<   "--#{boundary}\r\n"
    if filename
      s << "Content-Disposition: form-data; name=\"#{name}\"; filename=\"#{filename}\"\r\n"
    else
      s << "Content-Disposition: form-data; name=\"#{name}\"\r\n"
    end
    s <<   "Content-Type: #{content_type}\r\n" if content_type
    s <<   "\r\n"
    s <<   value.force_encoding('ASCII-8BIT')
    s <<   "\r\n"
  end
  s <<     "--#{boundary}--\r\n"
  return s
end