我正在开发一个带有控制器的应用程序,该控制器有很多 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
看起来也好不了多少。有没有办法重构它以提高可读性,或者我应该坚持使用当前的解决方案?