gpt4 book ai didi

ruby-on-rails - 多个 before_action 调用错误的代码风格吗?

转载 作者:行者123 更新时间:2023-12-04 04:36:59 24 4
gpt4 key购买 nike

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

def first_action
@first_variable = Something.new
end

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

Controller 如下所示:
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

从我的角度来看,这真的很难理解。这些方法中的每一个都有很多代码。此外,还有一些 Controller 继承自这个 Controller ,并且还使用部分或全部这些操作。

我听说最好明确说明每种方法中加载的变量,但是:
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

看起来好不了多少。有没有办法重构它以获得更高的可读性,或者我应该坚持当前的解决方案?

最佳答案

您当前的解决方案没问题。您可以使用 like 来避免多个方法调用

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

关于ruby-on-rails - 多个 before_action 调用错误的代码风格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40362946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com