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

时间:2012-01-10 13:15:22

标签: ruby-on-rails activerecord configuration callback

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

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

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

请告知。

1 个答案:

答案 0 :(得分:5)

实现条件回调的标准方法是将符号或过程传递给: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

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