Skip to content

Commit da31acc

Browse files
committed
Extend urlname getter to substitute wildcard params
The urlname getter is resolving the urlname attribute as before, but it has now the ability to substitute wildcard parameter if the urlname has those.
1 parent f1c758c commit da31acc

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

app/models/alchemy/page/page_naming.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,19 @@ def slug
4949
wildcard_url&.pattern.presence || urlname.to_s.split("/").last
5050
end
5151

52+
# Returns the urlname of the page.
53+
# If the page has a wildcard_url, you can pass params to substitute
54+
# the wildcards in the urlname: page.urlname(id: 42) # => "products/42"
55+
def urlname(**params)
56+
value = self[:urlname]
57+
return value if params.empty? || !has_wildcard_url?
58+
59+
params.each do |key, val|
60+
value = value.gsub(":#{key}", val.to_s)
61+
end
62+
value
63+
end
64+
5265
def has_wildcard_url?
5366
wildcard_url&.present?
5467
end

spec/models/alchemy/page_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1895,6 +1895,25 @@ module Alchemy
18951895
expect(child.urlname).to eq("products/:id/comments")
18961896
end
18971897
end
1898+
1899+
it "substitutes wildcards when called with params" do
1900+
expect(pattern_page.urlname(id: 42)).to eq("products/42")
1901+
end
1902+
end
1903+
1904+
context "with a multi-segment wildcard_url" do
1905+
let(:parent) { create(:alchemy_page, name: "Blog") }
1906+
let(:blog_page) { create(:alchemy_page, parent: parent, name: "Blog Post", page_layout: "blog_post") }
1907+
1908+
it "substitutes multiple wildcards when called with params" do
1909+
expect(blog_page.urlname(year: 2026, slug: "hello-world")).to eq("blog/2026/hello-world")
1910+
end
1911+
end
1912+
1913+
context "without a wildcard_url" do
1914+
it "returns the raw urlname even when called with params" do
1915+
expect(page.urlname(id: 42)).to eq(page.urlname)
1916+
end
18981917
end
18991918

19001919
context "if new urlname exists as a legacy url" do

0 commit comments

Comments
 (0)