Ruby on rails 多个before_操作调用是否为错误的代码样式?
我正在开发一款带有控制器的应用程序,它有很多在使用前的动作。它们中的大多数通过它们设置的实例变量相互连接。例如:Ruby on rails 多个before_操作调用是否为错误的代码样式?,ruby-on-rails,refactoring,Ruby On Rails,Refactoring,我正在开发一款带有控制器的应用程序,它有很多在使用前的动作。它们中的大多数通过它们设置的实例变量相互连接。例如: def first_action @first_variable = Something.new end def second_action if @first_variable @second_variable = Other.new end end 控制器如下所示: class ExampleController < ApplicationContr
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
从我的观点来看,这真的很难理解。每个方法都有很多代码。此外,还有一些控制器继承自此控制器,并且还使用部分或所有这些操作
我听说最好在每个方法中明确说明加载的变量,但是:
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
class ExampleController
看起来没什么好转。有没有办法对其进行重构以提高可读性,或者我应该坚持使用当前的解决方案?您当前的解决方案还可以。可以使用like来避免多个方法调用
before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create]
有多个before_action没有错-但看起来更像是你有一个案例,可以将它们收集到一个action中?有多个before_action
没有错-但是看起来更像是你有一个案例,可以将它们收集到一个action中?我同意你的想法@Matt谢谢如果你把它作为一个答案,我可以检查它作为我的问题的解决方案:)完成了,很高兴听到它有帮助!