以配置参数为条件进行ActiveRecord回调并对其进行测试

问题描述:

我想让after_update回调只在特定配置参数为true时执行。 起初,我有这样的事情:以配置参数为条件进行ActiveRecord回调并对其进行测试

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 

但是,我不完全明白我在这里做什么。这个改变何时会发生?只有在服务器重新启动?我如何测试这种行为?我不能只是设置配置,模型文件将不会再被读取。

请指教。

实现有条件的回调的标准方法是通过符号或PROC到: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 

这将允许设置应用程序的行为而不必重新启动服务器或删除常量并重新加载文件。