Skip to content

Commit ca704f2

Browse files
committed
Extend url path class to also handle wildcard params
Allow the setting of wildcard parameter in url_path class. It is using the already given optional_params attribute and the previous addition to the urlname method to add parameter to the wildcard url.
1 parent da31acc commit ca704f2

2 files changed

Lines changed: 32 additions & 4 deletions

File tree

app/models/alchemy/page/url_path.rb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def initialize(page, optional_params = {})
2424
@page = page
2525
@language = @page.language
2626
@site = @language.site
27-
@optional_params = optional_params
27+
@wildcard_params, @query_params = split_params(optional_params)
2828
end
2929

3030
def call
@@ -36,9 +36,9 @@ def call
3636
page_path_with_leading_slash
3737
end
3838

39-
if @optional_params.present?
39+
if @query_params.present?
4040
uri = URI(path)
41-
uri.query = @optional_params.to_query
41+
uri.query = @query_params.to_query
4242
uri.to_s
4343
else
4444
path
@@ -64,7 +64,13 @@ def language_path
6464
end
6565

6666
def page_path
67-
"#{root_path}#{@page.urlname}"
67+
"#{root_path}#{@page.urlname(**@wildcard_params)}"
68+
end
69+
70+
def split_params(params)
71+
return [{}, params] unless @page.has_wildcard_url? && params.present?
72+
73+
params.partition { |key, _| @page.wildcard_url.param_keys.include?(key) }.map(&:to_h)
6874
end
6975

7076
def root_path

spec/models/alchemy/page/url_path_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,28 @@
7676
end
7777
end
7878

79+
context "with wildcard params" do
80+
let(:parent) { create(:alchemy_page, name: "Products") }
81+
let(:page) { create(:alchemy_page, parent: parent, name: "Product Detail", page_layout: "product_detail") }
82+
83+
subject(:url) { described_class.new(page, {id: 42}).call }
84+
85+
it "substitutes wildcards in the urlname" do
86+
is_expected.to eq("/products/42")
87+
end
88+
end
89+
90+
context "with wildcard and query params mixed" do
91+
let(:parent) { create(:alchemy_page, name: "Products") }
92+
let(:page) { create(:alchemy_page, parent: parent, name: "Product Detail", page_layout: "product_detail") }
93+
94+
subject(:url) { described_class.new(page, {id: 42, page: 2}).call }
95+
96+
it "substitutes wildcards and appends remaining params as query string" do
97+
is_expected.to eq("/products/42?page=2")
98+
end
99+
end
100+
79101
context "mounted on a non-root path" do
80102
let(:page) do
81103
create(:alchemy_page)

0 commit comments

Comments
 (0)