Module: Rack::Test::Utils

Includes:
Utils
Included in:
Session
Defined in:
lib/rack/test/utils.rb

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

.build_multipart(params, first = true) ⇒ Object



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rack/test/utils.rb', line 29

def build_multipart(params, first = true)
  if first
    unless params.is_a?(Hash)
      raise ArgumentError, "value must be a Hash"
    end

    multipart = false
    query = lambda { |value|
      case value
      when Array
        value.each(&query)
      when Hash
        value.values.each(&query)
      when UploadedFile
        multipart = true
      end
    }
    params.values.each(&query)
    return nil unless multipart
  end

  flattened_params = Hash.new

  params.each do |key, value|
    k = first ? key.to_s : "[#{key}]"

    case value
    when Array
      value.map do |v|

        if (v.is_a?(Hash))
          nested_params = {}
          build_multipart(v, false).each { |subkey, subvalue|
            nested_params[subkey] = subvalue
          }
          flattened_params["#{k}[]"] ||= []
          flattened_params["#{k}[]"] << nested_params
        else
          flattened_params["#{k}[]"] = value
        end

      end
    when Hash
      build_multipart(value, false).each { |subkey, subvalue|
        flattened_params[k + subkey] = subvalue
      }
    else
      flattened_params[k] = value
    end
  end

  if first
    build_parts(flattened_params)
  else
    flattened_params
  end
end

.build_nested_query(value, prefix = nil) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rack/test/utils.rb', line 7

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("&")
  when Hash
    value.map do |k, v|
      build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
    end.join("&")
  when NilClass
    prefix.to_s
  else
    "#{prefix}=#{escape(value)}"
  end
end