我正在处理一个带有很多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
从我的观点来看,这很难理解。每种方法都有很多代码。另外,有一些控制器继承了这一个,并且还使用了部分或全部这些操作。
我听说在每种方法中明确加载变量是更好的,但是:
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
看起来好不了多少。有没有办法重构它以提高可读性?还是我应该坚持使用当前的解决方案?
答案 0 :(得分:24)
您当前的解决方案没问题。您可以使用
before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create]
答案 1 :(得分:5)
拥有多个before_actions没有任何问题 - 但看起来更像是你可以将它们收集到一个动作中?