Rails 4 - 如何优化此代码

时间:2015-07-31 14:28:06

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.2

让我们说我有这段代码:

class BooksController < ApplicationController

    def action1
        @books = ...
        @books = @books.someaction param1, param2
    end

    def action2
        @books = ...
        @books = @books.someaction param1, param2
    end

    def action3
        @books = ...
        @books = @books.someaction param1, param2
    end

    ...

    def action84
        @books = ...
        @books = @books.someaction param1, param2
    end

我有这个动作,我经常在一个实例变量上运行。我想把它放在after_action过滤器上,但是在渲染之后会发生这种情况,所以这不好。

我该如何优化呢?

免责声明:这是一个夸张的案例,而不是真实案例。只是想让问题更具图形性。我没有 84 操作的控制器。

3 个答案:

答案 0 :(得分:2)

您可以仅为该特定控制器覆盖render,以便在渲染之前始终执行您的操作。像这样:

class BooksController < ApplicationController

  def action1
    @books = ...
  end

  def action2
    @books = ...
  end

  private

  def render(*args)
    if @books.present? && param1.present? && param2.present?
      @books = @books.someaction param1, param2
    end
    super
  end

end

答案 1 :(得分:1)

只需在您的控制器中声明一个私有函数,并在您的操作中使用它:

class BooksController < ApplicationController
  def action1
    @books = ...
    foo
  end

  def action2
    @books = ...
    foo
  end

  def action3
    @books = ...
    foo
  end

  ...

  def action84
    @books = ...
    foo
  end

  private

  def foo
    @books = @books.someaction param1, param2
  end
end

答案 2 :(得分:1)

我会看decent_exposure gem。这应该允许你做一些像:

class BooksController < ApplicationController
    expose(:books) { books.someaction param1, param2 }

    def action1
        books = ...
    end

    def action2
        books = ...
    end

    def action3
        books = ...
    end

    ...

    def action84
        books = ...
    end
end