Merge pull request #6247 from cillian/deep-munge-issue

Patch Rails :deep_munge issue so empty array parameters don't get converted to nil
This commit is contained in:
Luis Ramos
2020-11-05 13:25:39 +00:00
committed by GitHub
3 changed files with 75 additions and 0 deletions

View File

@@ -0,0 +1 @@
require "action_dispatch/request"

View File

@@ -0,0 +1,49 @@
# frozen_string_literal: true
# This patch fixes the Rails issue where ActionDispatch::Request#deep_munge was converting empty
# array paramters into nils, see https://github.com/rails/rails/issues/13420
#
# Before this patch:
#
# | JSON | Hash |
# |----------------------------------|-------------------------|
# | { "person": [] } | { 'person' => nil } |
#
# After patch:
#
# | JSON | Hash |
# |----------------------------------|-------------------------|
# | { "person": [] } | { 'person' => [] } |
#
# The issue started in Rails v4.0.0.beta1:
#
# https://github.com/rails/rails/commit/8e577fe560d5756fcc67840ba304d79ada6804e4
#
# This patch can be removed on or after Rails v5.0.0.beta1 when the issue was fixed:
#
# https://github.com/rails/rails/commit/8f8ccb9901cab457c6e1d52bdb25acf658fd5777
#
# Credit:
#
# https://gist.github.com/victorblasco/f675b4cbaf9c0bc19f81
module ActionDispatch
class Request
def deep_munge(hash)
hash.each do |_k, v|
case v
when Array
v.grep(Hash) { |x| deep_munge(x) }
v.compact!
# This patch removes the next line
# hash[k] = nil if v.empty?
when Hash
deep_munge(v)
end
end
hash
end
end
end

View File

@@ -0,0 +1,25 @@
# frozen_string_literal: true
require 'spec_helper'
describe ActionDispatch::Request do
it "strips nils from arrays" do
expect(parse_query_parameters('key[]=value&key[]')).to eq({ "key" => ["value"] })
end
it "strips nils from nested arrays" do
expect(
parse_query_parameters('key1[key2][]=value&key1[key2][]')
).to eq({ "key1" => { "key2" => ["value"] } })
end
it "doesn't convert an empty array to nil" do
expect(parse_query_parameters('key[]')).to eq({ "key" => [] })
end
private
def parse_query_parameters(query_parameters)
ActionDispatch::Request.new("QUERY_STRING" => query_parameters).query_parameters
end
end