在我的 Rails 7 應用程式中,我有兩個控制器:
class Context::FrontendController < ApplicationController
end
class Context::BackendController < ApplicationController
end
我所有的其他控制器(其中有很多)都繼承自第一個或第二個(但絕不是兩者)。
在我看來,我有時需要根據當前控制器是否繼承自FrontendController OR來顯示或隱藏某些元素BackendController。
如何進行此項檢查?
uj5u.com熱心網友回復:
在我看來,我有時需要顯示或隱藏某些元素,具體取決于當前控制器是繼承自 FrontendController 還是 BackendController。
如何進行此項檢查?
您可以進行此檢查(如@mechnicov 所示),但您不應該這樣做。相反,請使用 OOP。
class ApplicationController
def current_area
# raise NotImplementedError
:none
end
helper_method :current_area
end
class FrontendController < ApplicationController
def current_area
:frontend
end
end
class BackendController < ApplicationController
def current_area
:backend
end
end
然后
<% if current_area == :frontend %>
您可以根據需要美化它(制作方法frontend?/backend?等)
uj5u.com熱心網友回復:
在您看來,您可以使用類似
<% if controller.class.ancestors.include?(Context::BackendController) %>
<%= show.some.content %>
<% end %>
可能會創建一些幫手
def inherited_from?(controller_class)
controller.class.ancestors.include?(controller_class)
end
接著
<% if inherited_from?(Context::BackendController) %>
<%= show.some.content %>
<% end %>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505026.html
