多个before_action调用坏代码样式?

我正在开发一个带有很多before_actions的控制器的应用程序。 它们中的大多数通过它们设置的实例变量彼此连接。 例如:

def first_action @first_variable = Something.new end def second_action if @first_variable @second_variable = Other.new end end 

控制器看起来像这样:

 class ExampleController < ApplicationController before_action :first_action, only: [:index, :show, :create] before_action :second_action, only: [:index, :show, :create] before_action :third_action, only: [:index, :show, :create] before_action :fourth_action, only: [:index, :show, :create] before_action :fifth_action, only: [:index, :show, :create] before_action :sixth_action, only: [:index, :show, :create] before_action :seventh_action, only: [:index, :show, :create] def index # some code end def show # some code end def create # some code end private # all of the before_action methods end 

从我的观点来看,这真的很难理解。 这些方法中的每一个都有很多代码。 另外,有一些控制器inheritance了这个控制器,并且还使用了部分或全部这些操作。

我听说最好在每个方法中明确加载变量,但是这样:

 class ExampleController < ApplicationController def index first_action second_action third_action fourth_action fifth_action sixth_action seventh_action # some code end def show first_action second_action third_action fourth_action fifth_action sixth_action seventh_action # some code end def create first_action second_action third_action fourth_action fifth_action sixth_action seventh_action # some code end private # all of the before_action methods end 

看起来不太好。 有没有办法重构它以提高可读性,还是应该坚持使用当前的解决方案?

有多个before_actions没有任何问题 – 但看起来更像是你有一个案例可以将它们收集到一个动作中?

您当前的解决方案没问题。 你可以使用喜欢

 before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create]