Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions lib/hanami/router/url_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

module Hanami
class Router
# @since 2.0.0
# @api private
class UrlHelpers
# @since 2.0.0
Expand All @@ -19,27 +18,40 @@ def initialize(base_url)
@prefix = Prefix.new(prefix)
end

# @since 2.0.0
# @api private
def add(name, segment)
@named[name] = segment
end

# @since 2.0.0
# @api private
def path(name, variables = {})
@named.fetch(name.to_sym) do
raise MissingRouteError.new(name)
end.expand(:append, variables)
scalar_vars = variables.reject { |_, value| value.is_a?(Array) }
array_vars = array_query_vars(variables)

expanded_path = @named
.fetch(name.to_sym) { raise MissingRouteError.new(name) }
.expand(:append, scalar_vars)

return expanded_path if array_vars.empty?

join_char = expanded_path.include?("?") ? "&" : "?"
"#{expanded_path}#{join_char}#{Rack::Utils.build_query(array_vars)}"
rescue Mustermann::ExpandError => exception
raise InvalidRouteExpansionError.new(name, exception.message)
end

# @since 2.0.0
# @api private
def url(name, variables = {})
@base_url + @prefix.join(path(name, variables)).to_s
end

private

def array_query_vars(variables = {})
variables
.select { |_, value| value.is_a?(Array) }
.to_h { |key, value| ["#{key}[]", value] }
end
end
end
end
18 changes: 18 additions & 0 deletions spec/integration/hanami/router/routing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,24 @@
end
end

context "array variable alone" do
let(:response) { Rack::MockResponse.new(200, rack_headers({}), "Named %route!") }

it "recognizes" do
expect(router.path(:"#{verb}_named_route", foo: ["bar", "baz"])).to eq("/named_route?foo%5B%5D=bar&foo%5B%5D=baz")
expect(router.url(:"#{verb}_named_route", foo: ["bar", "baz"])).to eq(URI("http://localhost/named_route?foo%5B%5D=bar&foo%5B%5D=baz"))
end
end

context "array variable mixed" do
let(:response) { Rack::MockResponse.new(200, rack_headers({}), "Named %route!") }

it "recognizes" do
expect(router.path(:"#{verb}_named_route", foo: ["bar", "baz"], var: "plop")).to eq("/named_route?var=plop&foo%5B%5D=bar&foo%5B%5D=baz")
expect(router.url(:"#{verb}_named_route", foo: ["bar", "baz"], var: "plop")).to eq(URI("http://localhost/named_route?var=plop&foo%5B%5D=bar&foo%5B%5D=baz"))
end
end

context "custom url parts" do
let(:response) { Rack::MockResponse.new(200, rack_headers({}), "Named route with custom parts!") }

Expand Down