Skip to content

Commit

Permalink
Adds support for empty arrays in params.
Browse files Browse the repository at this point in the history
Without the patch empty arrays will be removed implicitly.
Adding this special case to ``build_nested_query`` fixes this
issue.

Implements PR #125, thanks to @croeck and @Timsly
  • Loading branch information
Dennis Sivia authored and perlun committed Apr 21, 2017
1 parent c6dc62c commit ece681d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
23 changes: 13 additions & 10 deletions lib/rack/test/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,16 @@ module Utils # :nodoc:
def build_nested_query(value, prefix = nil)
case value
when Array
value.map do |v|
unless unescape(prefix) =~ /\[\]$/
prefix = "#{prefix}[]"
end
build_nested_query(v, "#{prefix}")
end.join("&")
if value.empty?
"#{prefix}[]="
else
value.map do |v|
unless unescape(prefix) =~ /\[\]$/
prefix = "#{prefix}[]"
end
build_nested_query(v, "#{prefix}")
end.join("&")
end
when Hash
value.map do |k, v|
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
Expand All @@ -24,7 +28,6 @@ def build_nested_query(value, prefix = nil)
"#{prefix}=#{escape(value)}"
end
end

module_function :build_nested_query

def build_multipart(params, first = true)
Expand Down Expand Up @@ -86,7 +89,7 @@ def build_multipart(params, first = true)
end
module_function :build_multipart

private
private
def build_parts(parameters)
get_parts(parameters).join + "--#{MULTIPART_BOUNDARY}--\r"
end
Expand Down Expand Up @@ -123,7 +126,7 @@ def build_primitive_part(parameter_name, value)
value = [value]
end
value.map do |v|
<<-EOF
<<-EOF
--#{MULTIPART_BOUNDARY}\r
Content-Disposition: form-data; name="#{parameter_name}"\r
\r
Expand All @@ -136,7 +139,7 @@ def build_primitive_part(parameter_name, value)
def build_file_part(parameter_name, uploaded_file)
::File.open(uploaded_file.path, "rb") do |physical_file|
physical_file.set_encoding(Encoding::BINARY) if physical_file.respond_to?(:set_encoding)
<<-EOF
<<-EOF
--#{MULTIPART_BOUNDARY}\r
Content-Disposition: form-data; name="#{parameter_name}"; filename="#{escape(uploaded_file.original_filename)}"\r
Content-Type: #{uploaded_file.content_type}\r
Expand Down
5 changes: 5 additions & 0 deletions spec/rack/test/utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
it "converts arrays of hashes" do
expect(build_nested_query(:a => [{ :b => 2}, { :c => 3}])).to eq("a[][b]=2&a[][c]=3")
end

it "supports hash keys with empty arrays" do
input = { collection: [] }
expect(build_nested_query(input)).to eq('collection[]=')
end
end

describe "Rack::Test::Utils.build_multipart" do
Expand Down

0 comments on commit ece681d

Please sign in to comment.