本文介绍了是否有多个 before_action 调用错误的代码风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on an app with controller that have lots of before_actions. Most of them are connected with each other by instance variables that they set. For example:

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

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

It's really hard to understand from mine point of view. Each of those method has lots of code. Additionaly there are controllers that inherits from this one and also use part or all of those actions.

我听说最好在每个方法中明确说明加载的变量,但是这样:

I heard that it's better to be explicit about loaded variables in each method but this:

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

看起来并没有好多少.有没有办法重构它以提高可读性,还是应该坚持使用当前的解决方案?

doesn't look much better. Is there a way to refactor it for more readability or should I stick with current solution?

推荐答案

拥有多个 before_actions 并没有错 - 但看起来更像是您可以将它们收集到一个动作中的情况?

There is nothing wrong with having multiple before_actions - but it looks more like you have a case where they could be collected into one action?

这篇关于是否有多个 before_action 调用错误的代码风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:32