Ruby on rails 在Rails 5中重用私有方法
到目前为止,大多数问题都与“有什么区别”有关。我需要知道如何在不同的控制器之间重用它们 下面只是一个例子 应用程序控制器:Ruby on rails 在Rails 5中重用私有方法,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,到目前为止,大多数问题都与“有什么区别”有关。我需要知道如何在不同的控制器之间重用它们 下面只是一个例子 应用程序控制器: private def redirect redirect_to welcome_path end class AnyController < ApplicationController before_action :redirect, only: :about def about end end 任何控制器: private def redir
private
def redirect
redirect_to welcome_path
end
class AnyController < ApplicationController
before_action :redirect, only: :about
def about
end
end
任何控制器:
private
def redirect
redirect_to welcome_path
end
class AnyController < ApplicationController
before_action :redirect, only: :about
def about
end
end
class AnyController
我现在有许多控制器,它们使用相同的私有方法,并希望将其存储在一个中心位置。你知道,保持它干燥之类的。在哪里放置这些私有方法,以便在继承自ApplicationController的任何控制器上重用?如果这样的问题已经得到了回答,请告诉我。谢谢
在何处放置这些私有方法以跨任何控制器重用
从ApplicationController继承的
如果希望继承自ApplicationController
的类具有该方法,只需将其放入ApplicationController
:
class ApplicationController < ActionController::Base
private
def redirect_to welcome_path
end
end
class AnyController < ApplicationController
# gets the redirect_to welcome_path method
end
class ApplicationController
这就是ApplicationController
存在的原因
Re:modules,它不需要在一个模块中,除非您最终想要将它混合到除
ApplicationController
之外的另一个类中,否则将private
用作public
是否存在矛盾?您是否理解private
和public
方法之间的区别?是的,我理解。我还从我找到的一本旧书中找到了答案。我将私有方法放在app/controllers/concerns/private\u rules.rb中的一个模块中,然后将该模块包括在applicationcontroller
中。快乐的日子。