zet*_*eth 14 refactoring ruby-on-rails
我正在开发一个带有很多before_actions的控制器的应用程序.它们中的大多数通过它们设置的实例变量彼此连接.例如:
def first_action
@first_variable = Something.new
end
def second_action
if @first_variable
@second_variable = Other.new
end
end
Run Code Online (Sandbox Code Playgroud)
控制器看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
从我的观点来看,这真的很难理解.每种方法都有很多代码.另外,有一些控制器继承了这一个,并且还使用了部分或全部这些操作.
我听说最好在每个方法中明确加载变量,但是这样:
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
Run Code Online (Sandbox Code Playgroud)
看起来不太好.有没有办法重构它以提高可读性,还是应该坚持使用当前的解决方案?
emp*_*mpr 30
您当前的解决方案没问题.你可以使用喜欢
before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create]
Run Code Online (Sandbox Code Playgroud)