class FaceAi::MultiPart

Public Class Methods

guess_mime(filename) click to toggle source
# File lib/baiduAiFace/client.rb, line 60
def self.guess_mime filename
  res = MIME::Types.type_for(filename)
  res.empty? ? 'application/octet-stream' : res[0]
end
new() click to toggle source
# File lib/baiduAiFace/client.rb, line 46
def initialize
  @fields = []
  @files = []
  @boundary = [SecureRandom.random_bytes(15)].pack('m*').chop!
end

Public Instance Methods

add_field(name, value) click to toggle source
# File lib/baiduAiFace/client.rb, line 52
def add_field name, value
  @fields << [name, value]
end
add_file(name, filepath) click to toggle source
# File lib/baiduAiFace/client.rb, line 56
def add_file name, filepath
  @files << [name, filepath]
end
content_type() click to toggle source
# File lib/baiduAiFace/client.rb, line 69
def content_type
  "multipart/form-data; boundary=#{@boundary}"
end
has_file?() click to toggle source
# File lib/baiduAiFace/client.rb, line 65
def has_file?
  not @files.empty?
end
inspect() click to toggle source
# File lib/baiduAiFace/client.rb, line 73
def inspect
  res = StringIO.new
  append_boundary = lambda { res.write "--#{@boundary}\r\n" }
  @fields.each do |field|
    append_boundary[]
    res.write "Content-Disposition: form-data; name=\"#{field[0]}\"\r\n\r\n#{field[1]}\r\n"
  end
  @files.each do |file|
    append_boundary[]
    res.write "Content-Disposition: file; name=\"#{file[0]}\"; filename=\"#{file[1]}\"\r\n"
    res.write "Content-Type: #{self.class.guess_mime file[1]}\r\n"
    res.write "Content-Transfer-Encoding: binary\r\n\r\n"
    res.write File.open(file[1]).read
    res.write "\r\n"
  end
  res.write "--#{@boundary}--\r\n"
  res.rewind
  res.read
end