【问题标题】:Make ActiveRecord callback conditional on configuration parameter and test it使 ActiveRecord 回调以配置参数为条件并测试它
【发布时间】:2012-02-06 21:33:27
【问题描述】:

我想让 after_update 回调仅在某个配置参数为 true 时执行。 起初我有这样的事情:

after_update :do_something
...

def do_something
  return unless MyApp::Application.config.some_config
  actualy_do_something
end

但后来我想,为什么不让回调赋值有条件呢? 像这样:

after_update :do_something if MyApp::Application.config.some_config

但是我不完全理解我在这里做什么。这会在什么时候改变?仅在服务器重新启动时?如何测试这种行为?我不能只设置配置,模型文件不会被再次读取。

请指教。

【问题讨论】:

    标签: ruby-on-rails activerecord configuration callback


    【解决方案1】:

    实现条件回调的标准方法是将符号或过程传递给:if

    before_create :generate_authentication_token, :if => :authentication_token_missing?
    after_destroy :deliver_thank_you_email, :if => lambda {|user| user.wants_email? }
    
    def authentication_token_missing?
      authentication_token.empty?
    end
    

    此格式还可以引用Rails.configuration 上的全局配置设置

    after_update :refresh_cache, :if => :cache_available?
    
    def cache_available?
      Rails.configuration.custom_cache.present?
    end
    

    这将允许更改应用程序的行为,而无需重新启动服务器或删除常量并重新加载文件。

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2015-02-21
      相关资源
      最近更新 更多