lib/httpx/plugins/multipart.rb in httpx-0.10.2 vs lib/httpx/plugins/multipart.rb in httpx-0.11.0

- old
+ new

@@ -8,55 +8,60 @@ # HTTPX.post(URL, form: form: { image: HTTP::FormData::File.new("path/to/file")}) # # https://gitlab.com/honeyryderchuck/httpx/wikis/Multipart-Uploads # module Multipart - module FormTranscoder - module_function + MULTIPART_VALUE_COND = lambda do |value| + value.respond_to?(:read) || + (value.respond_to?(:to_hash) && + value.key?(:body) && + (value.key?(:filename) || value.key?(:content_type))) + end - class Encoder - extend Forwardable + class << self + def normalize_keys(key, value, &block) + Transcoder.normalize_keys(key, value, MULTIPART_VALUE_COND, &block) + end - def_delegator :@raw, :content_type - - def_delegator :@raw, :to_s - - def_delegator :@raw, :read - - def initialize(form) - @raw = if multipart?(form) - HTTP::FormData::Multipart.new(Hash[form.flat_map { |k, v| Transcoder.enum_for(:normalize_keys, k, v).to_a }]) - else - HTTP::FormData::Urlencoded.new(form, :encoder => Transcoder::Form.method(:encode)) + def load_dependencies(*) + begin + unless defined?(HTTP::FormData) + # in order not to break legacy code, we'll keep loading http/form_data for them. + require "http/form_data" + warn "httpx: http/form_data is no longer a requirement to use HTTPX :multipart plugin. See migration instructions under" \ + "https://honeyryderchuck.gitlab.io/httpx/wiki/Multipart-Uploads.html#notes. \n\n" \ + "If you'd like to stop seeing this message, require 'http/form_data' yourself." end + rescue LoadError end + require "httpx/plugins/multipart/encoder" + require "httpx/plugins/multipart/part" + require "httpx/plugins/multipart/mime_type_detector" + end - def bytesize - @raw.content_length - end + def configure(*) + Transcoder.register("form", FormTranscoder) + end + end - private + module FormTranscoder + module_function - def multipart?(data) - data.any? do |_, v| - v.is_a?(HTTP::FormData::Part) || - (v.respond_to?(:to_ary) && v.to_ary.any? { |e| e.is_a?(HTTP::FormData::Part) }) || - (v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| e.is_a?(HTTP::FormData::Part) }) - end + def encode(form) + if multipart?(form) + Encoder.new(form) + else + Transcoder::Form::Encoder.new(form) end end - def encode(form) - Encoder.new(form) + def multipart?(data) + data.any? do |_, v| + MULTIPART_VALUE_COND.call(v) || + (v.respond_to?(:to_ary) && v.to_ary.any?(&MULTIPART_VALUE_COND)) || + (v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| MULTIPART_VALUE_COND.call(e) }) + end end - end - - def self.load_dependencies(*) - require "http/form_data" - end - - def self.configure(*) - Transcoder.register("form", FormTranscoder) end end register_plugin :multipart, Multipart end end