Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails 5中重用私有方法_Ruby On Rails_Ruby On Rails 5 - Fatal编程技术网

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
中。快乐的日子。