在 Rails 5 中重用私有方法

Reusing Private Methods in Rails 5

到目前为止,大多数 searched questions 都与 "what's the difference" 有关。我需要知道如何在不同的控制器中重用它们。

下面只是一个例子。

应用程序控制器:

private
 def redirect
  redirect_to welcome_path
 end

任何控制器:

class AnyController < ApplicationController
 before_action :redirect, only: :about

 def about
 end
end

我现在有很多使用相同私有方法的控制器,并且想要一个集中的地方来存储它。你知道,保持干燥之类的事情。将这些私有方法放在哪里以在从 ApplicationController 继承的任何控制器中重用?如果已经回答了这样的问题,请指出我的位置。谢谢

Where to place these private methods to reuse across any controller that inherits from ApplicationController?

如果你想让继承自ApplicationController的class有这个方法,你只需要把它放在ApplicationController:

class ApplicationController < ActionController::Base

 private

 def redirect_to welcome_path
 end
end

class AnyController < ApplicationController
  # gets the redirect_to welcome_path method
end

这就是 ApplicationController 存在的原因。

回复:模块,它不需要在模块中,除非你最终想将它混合到 ApplicationController 之外的另一个 class。