Class: BraintreeHttp::Multipart

Inherits:
Object
  • Object
show all
Defined in:
lib/braintreehttp/encoder.rb

Instance Method Summary collapse

Instance Method Details

#_add_file_part(key, file) ⇒ Object



121
122
123
124
125
# File 'lib/braintreehttp/encoder.rb', line 121

def _add_file_part(key, file)
  mime_type = _mime_type_for_file_name(file.path)
  return "Content-Disposition: form-data; name=\"#{key}\"; filename=\"#{File.basename(file.path)}\"#{LINE_FEED}" +
    "Content-Type: #{mime_type}#{LINE_FEED}#{LINE_FEED}#{file.read}#{LINE_FEED}"
end

#_add_form_field(key, value) ⇒ Object



117
118
119
# File 'lib/braintreehttp/encoder.rb', line 117

def _add_form_field(key, value)
  return "Content-Disposition: form-data; name=\"#{key}\"#{LINE_FEED}#{LINE_FEED}#{value}#{LINE_FEED}"
end

#_mime_type_for_file_name(filename) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/braintreehttp/encoder.rb', line 127

def _mime_type_for_file_name(filename)
  file_extension = File.extname(filename).strip.downcase[1..-1]
  if file_extension == "jpeg" || file_extension == "jpg"
    return "image/jpeg"
  elsif file_extension == "png"
    return "image/png"
  elsif file_extension == "pdf"
    return "application/pdf"
  else
    return "application/octet-stream"
  end
end

#content_typeObject



113
114
115
# File 'lib/braintreehttp/encoder.rb', line 113

def content_type
  /^multipart\/.*/
end

#decode(body) ⇒ Object



109
110
111
# File 'lib/braintreehttp/encoder.rb', line 109

def decode(body)
  raise UnsupportedEncodingError.new("Multipart does not support deserialization")
end

#encode(request) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/braintreehttp/encoder.rb', line 93

def encode(request)
  boundary = DateTime.now.strftime("%Q")
  request.headers["Content-Type"] = "multipart/form-data; boundary=#{boundary}"

  form_params = []
  request.body.each do |k, v|
    if v.is_a? File
      form_params.push(_add_file_part(k, v))
    else
      form_params.push(_add_form_field(k, v))
    end
  end

  form_params.collect {|p| "--" + boundary + "#{LINE_FEED}" + p}.join("") + "--" + boundary + "--"
end