Created
May 26, 2014 00:51
-
-
Save coryf/5d6fcb56a356e00023bb to your computer and use it in GitHub Desktop.
Rails deep_munge patch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a monkey patch to fix the Rails deep_munge issue described here: | |
# https://github.com/rails/rails/issues/13420 | |
# | |
# Rails converts incoming empty array params into nils. This patch reverts that. | |
# This goes in /config/initializers | |
# | |
# Before patch: | |
# | |
# | JSON | Hash | | |
# |----------------------------------|-------------------------| | |
# | { "person": null } | { 'person' => nil } | | |
# | { "person": [] } | { 'person' => nil } | | |
# | { "person": [null] } | { 'person' => nil } | | |
# | { "person": [null, null, ...] } | { 'person' => nil } | | |
# | { "person": ["foo", null] } | { 'person' => ["foo"] } | | |
# | |
# After patch: | |
# | |
# | JSON | Hash | | |
# |----------------------------------|-------------------------| | |
# | { "person": null } | { 'person' => nil } | | |
# | { "person": [] } | { 'person' => [] } | | |
# | { "person": [null] } | { 'person' => [] } | | |
# | { "person": [null, null, ...] } | { 'person' => [] } | | |
# | { "person": ["foo", null] } | { 'person' => ["foo"] } | | |
class DeepMungeFix | |
def self.patch | |
if test_query_params("test[]") == { "test" => nil } | |
apply_patch | |
unless test_query_params("test[]") == { "test" => [] } | |
raise "patch failed!" | |
end | |
else | |
raise "deep_munge patch not applied. Maybe this was fixed in this version of Rails?" | |
end | |
end | |
def self.test_query_params(query_string) | |
ActionDispatch::Request.new('QUERY_STRING' => query_string).query_parameters | |
end | |
def self.apply_patch | |
ActionDispatch::Request.class_eval do | |
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 | |
end | |
DeepMungeFix.patch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment