Skip to content

Commit

Permalink
Support nested query for expanding path, fixes #1982
Browse files Browse the repository at this point in the history
  • Loading branch information
namusyaka committed Oct 29, 2015
1 parent dbee3a4 commit 7f96814
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
28 changes: 27 additions & 1 deletion padrino-core/lib/padrino-core/path_router/matcher.rb
Expand Up @@ -38,9 +38,35 @@ def to_regexp
#
def expand(params)
params = params.merge(@default_values) if @default_values.is_a?(Hash)
expanded_path = handler.expand(:append, params)
params, query = params.each_with_object([{}, {}]) do |(key, val), parts|
parts[handler.names.include?(key.to_s) ? 0 : 1][key] = val
end
query = build_nested_query(query)
expanded_path = Rack::Utils.unescape(handler.expand(:append, params))
expanded_path += ?? + query unless query.empty?
expanded_path
end

##
# Builds nested query.
#
def build_nested_query(value, prefix = nil)
case value
when Array
value.map { |v|
build_nested_query(v, "#{prefix}[]")
}.join("&")
when Hash
value.map { |k, v|
build_nested_query(v, prefix ? "#{prefix}[#{k}]" : k)
}.reject(&:empty?).join('&')
when nil
prefix
else
raise ArgumentError, "value must be a Hash" if prefix.nil?
"#{prefix}=#{value}"
end
end

##
# Returns true if handler is an instance of Mustermann.
Expand Down
3 changes: 3 additions & 0 deletions padrino-core/test/test_routing.rb
Expand Up @@ -259,6 +259,7 @@ def match(string)
get(:anchor) { url(:anchor, :anchor => 'comments') }
get(:fragment) { url(:anchor, :fragment => 'comments') }
get(:fragment2) { url(:anchor, :fragment => :comments) }
get(:gangsta) { url(:gangsta, :foo => { :bar => :baz }, :hoge => :fuga) }
get([:hash, :id]){ url(:hash, :id => 1) }
get(:array, :with => :id){ url(:array, 23) }
get([:array, :id]){ url(:array, 23) }
Expand Down Expand Up @@ -307,6 +308,8 @@ def match(string)
assert_equal "/drugs/123/destroy", body
delete "/123/destroy"
assert_equal "/123/destroy", body
get "/gangsta"
assert_equal "/gangsta?foo[bar]=baz&hoge=fuga", body
get "/splatter/123/456"
assert_equal "/splatter/123/456", body
end
Expand Down

0 comments on commit 7f96814

Please sign in to comment.