Class: HTTP::Client::Multipart

Inherits:
Object
  • Object
show all
Defined in:
lib/http/client.rb

Overview

Response

Constant Summary collapse

EOL =
"\r\n"
DEFAULT_MIME_TYPE =
'application/octet-stream'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files, query = {}) ⇒ Multipart

Returns a new instance of Multipart.



327
328
329
330
331
# File 'lib/http/client.rb', line 327

def initialize files, query = {}
  @files    = files
  @query    = query || {}
  @boundary = generate_boundary
end

Instance Attribute Details

#boundaryObject (readonly)

Returns the value of attribute boundary.



322
323
324
# File 'lib/http/client.rb', line 322

def boundary
  @boundary
end

Instance Method Details

#bodyObject



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/http/client.rb', line 337

def body
  body      = ''.encode('ASCII-8BIT')
  separator = "--#{boundary}"

  if @query && !@query.empty?
    @query.each do |key, value|
      body << separator << EOL
      body << %Q{Content-Disposition: form-data; name="#{key}"} << EOL
      body << EOL
      body << value
      body << EOL
    end
  end

  if @files && !@files.empty?
    @files.each do |name, handle|
      if handle.respond_to?(:read)
        path = handle.path
        data = io.read
      else
        path = handle
        data = IO.read(path)
      end

      filename = File.basename(path)
      mime     = mime_type(filename)

      body << separator << EOL
      body << %Q{Content-Disposition: form-data; name="#{name}"; filename="#{filename}"} << EOL
      body << %Q{Content-Type: #{mime}}              << EOL
      body << %Q{Content-Transfer-Encoding: binary}  << EOL
      body << %Q{Content-Length: #{data.bytesize}}   << EOL
      body << EOL
      body << data
      body << EOL
    end
  end

  body << separator << "--" << EOL
  body
end

#content_typeObject



333
334
335
# File 'lib/http/client.rb', line 333

def content_type
  "multipart/form-data; boundary=#{boundary}"
end