【问题标题】:Executing a conditional method only one time for a callback with multiple methods. Rails对于具有多个方法的回调,只执行一次条件方法。导轨
【发布时间】:2018-04-04 10:39:50
【问题描述】:

在 Rails 应用程序中,我使用 after_update 回调,它在传递如下条件方法时运行多个方法:

app/models/my_model.rb

class MyModel < ApplicationRecord
  after_update :method_1, :method_2, :method_3, if: :this_happens?
  #some custom methods
private
  def this_happens?
    # a condition that returns true or false here
  end
end

我注意到 this_happens? 方法被执行了 3 次,就在 :method_1:method_2:method_3 之前。

这是有道理的,因为这三个回调方法中的任何一个都可能以这样一种方式更改数据,即必须再次评估条件以确保在每种情况下都满足它。但是,当您知道这 3 种方法不会以任何可能改变条件评估的方式更改数据时,是否可以只运行一次 this_happens? 并获得一些效率?

我似乎在网上找不到任何东西,不知道是否有人可以提供建议。

PS。使用 Rails 5.1

【问题讨论】:

    标签: ruby-on-rails callback


    【解决方案1】:

    封装是克服这种情况的最简单方法之一。

    只需将您的方法包装在另一个中,然后它只会检查一次this_happens?

    class MyModel < ApplicationRecord
      after_update :combine_methods, if: :this_happens?
      #some custom methods
    private
      def combine_methods
        method_1
        method_2
        method_3
      end
    
      def this_happens?
        # a condition that returns true or false here
      end
    end
    

    【讨论】:

    • 谢谢 mdegis。当然!我一直在寻找一个内置的解决方案,但你的方式很有意义。我怎么没想到!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 2023-01-27
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多