Skip to content

Commit

Permalink
Properly handle nested params
Browse files Browse the repository at this point in the history
  • Loading branch information
coderspeak-phitherek authored and ioquatix committed Jun 2, 2022
1 parent 746e1a4 commit 025716d
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions lib/multipart/post/multipartable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,11 @@ def initialize(path, params, headers={}, boundary = Multipartable.secure_boundar
headers = headers.clone # don't want to modify the original variable
parts_headers = headers.delete(:parts) || {}
super(path, headers)
parts = params.map do |k,v|
case v
when Array
v.map {|item| Parts::Part.new(boundary, k, item, parts_headers[k]) }
else
Parts::Part.new(boundary, k, v, parts_headers[k])
end
end.flatten

parts = Array.new
generate_parts(parts, params, boundary, parts_headers, '')
parts << Parts::EpiloguePart.new(boundary)

ios = parts.map {|p| p.to_io }
self.set_content_type(headers["Content-Type"] || "multipart/form-data",
{ "boundary" => boundary })
Expand All @@ -50,6 +46,29 @@ def initialize(path, params, headers={}, boundary = Multipartable.secure_boundar
end

attr :boundary

private

def generate_parts(parts, params, boundary, parts_headers, prefix)
params.each do |key, value|
generate_nested_parts(parts, key, value, boundary, parts_headers, prefix)
end
end

def generate_nested_parts(parts, key, value, boundary, parts_headers, prefix)
nested_prefix = prefix.empty? ? key.to_s : "#{prefix}[#{key}]"

case value
when Array
value.each do |item|
generate_nested_parts(parts, '', item, boundary, parts_headers, nested_prefix)
end
when Hash
generate_parts(parts, value, boundary, parts_headers, nested_prefix)
else
parts << Parts::Part.new(boundary, nested_prefix, value, parts_headers[key])
end
end
end
end
end

0 comments on commit 025716d

Please sign in to comment.