Skip to content

Commit 4144cf3

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 0a95122 commit 4144cf3

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

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&.has_service?
135+
begin
136+
@service = @page.definition.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: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,5 +257,30 @@ 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 "calls the service" do
266+
expect_any_instance_of(DummyPageService).to receive(:call)
267+
get :show, params: {urlname: page_with_service.urlname}
268+
end
269+
270+
it "assigns the service instance to @service" do
271+
get :show, params: {urlname: page_with_service.urlname}
272+
expect(assigns(:service)).to be_a(DummyPageService)
273+
end
274+
end
275+
276+
context "when the service raises Alchemy::PageNotFound" do
277+
it "renders a 404" do
278+
expect_any_instance_of(DummyPageService).to receive(:call).and_raise(Alchemy::PageNotFound)
279+
expect {
280+
get :show, params: {urlname: page_with_service.urlname}
281+
}.to raise_error(ActionController::RoutingError)
282+
end
283+
end
284+
end
260285
end
261286
end

0 commit comments

Comments
 (0)