aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_dispatch/request/utils.rb
blob: 01fd5efd5e000abb24d97a6b6657ed6bdb2a5754 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module ActionDispatch
  class Request < Rack::Request
    class Utils # :nodoc:

      mattr_accessor :perform_deep_munge
      self.perform_deep_munge = true

      def self.normalize_encode_params(params)
        ParamEncoder.normalize_encode_params params
      end

      class ParamEncoder
        # Convert nested Hash to HashWithIndifferentAccess.
        #
        def self.normalize_encode_params(params)
          case params
          when Array
            handle_array params
          when Hash
            if params.has_key?(:tempfile)
              ActionDispatch::Http::UploadedFile.new(params)
            else
              params.each_with_object({}) do |(key, val), new_hash|
                new_hash[key] = normalize_encode_params(val)
              end.with_indifferent_access
            end
          else
            params
          end
        end

        def self.handle_array(params)
          params.map! { |el| normalize_encode_params(el) }
        end
      end

      class << self
        # Remove nils from the params hash
        def deep_munge(hash)
          return hash unless perform_deep_munge

          hash.each do |k, v|
            case v
            when Array
              v.grep(Hash) { |x| deep_munge(x) }
              v.compact!
            when Hash
              deep_munge(v)
            end
          end

          hash
        end
      end
    end
  end
end