Skip to content

Commit 312b5dc

Browse files
committed
Initialize and call service in page_controller
Create a @service variable that is containing the initialized services. After that the service will be called. The service can fire an Alchemy::PageNotFound error that is interesting the current user is not allowed to see the page. The service also gets the parameters that maybe contain also wildcard_url parameter.
1 parent d6cf0b2 commit 312b5dc

3 files changed

Lines changed: 33 additions & 0 deletions

File tree

app/controllers/alchemy/pages_controller.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,16 @@ def load_page
130130
urlname: params[:urlname],
131131
language_code: params[:locale] || Current.language.code
132132
)
133+
134+
if @page&.service
135+
begin
136+
@service = @page.service.new(@page, params: params)
137+
@service.call
138+
rescue Alchemy::PageNotFound
139+
page_not_found!
140+
end
141+
end
142+
133143
Current.page = @page
134144
end
135145

lib/alchemy/errors.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,7 @@ def message
8585
"Unknown Version! Please use one of #{Alchemy::EagerLoading::PAGE_VERSIONS.join(", ")}"
8686
end
8787
end
88+
89+
# Raised by page definition services to trigger a 404 response.
90+
class PageNotFound < StandardError; end
8891
end

spec/controllers/alchemy/pages_controller_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,5 +257,25 @@ module Alchemy
257257
end
258258
end
259259
end
260+
261+
describe "Page definition service" do
262+
let(:page_with_service) { create(:alchemy_page, :public, page_layout: :with_service) }
263+
264+
context "when the page definition has a service" do
265+
it "assigns the service instance to @service" do
266+
get :show, params: {urlname: page_with_service.urlname}
267+
expect(assigns(:service)).to be_a(DummyPageService)
268+
end
269+
end
270+
271+
context "when the service raises Alchemy::PageNotFound" do
272+
it "renders a 404" do
273+
expect_any_instance_of(DummyPageService).to receive(:call).and_raise(Alchemy::PageNotFound)
274+
expect {
275+
get :show, params: {urlname: page_with_service.urlname}
276+
}.to raise_error(ActionController::RoutingError)
277+
end
278+
end
279+
end
260280
end
261281
end

0 commit comments

Comments
 (0)