简体   繁体   English

使ActiveRecord回调取决于配置参数并对其进行测试

[英]Make ActiveRecord callback conditional on configuration parameter and test it

I want to make a after_update callback only execute when a certain configuration parameter is true. 我想只在某个配置参数为true时才执行after_update回调。 At first I had something like this: 一开始我有这样的事情:

after_update :do_something
...

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

But then I thought, why not make the callback assignment conditional? 但是后来我想,为什么不使回调分配成为条件? Like this: 像这样:

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

However I don't fully understand what Im doing here. 但是我不完全了解我在这里做什么。 When would this change? 什么时候会改变? Only on server restarts? 仅在服务器上重启? How do I test this behavior ? 如何测试这种行为? I can't just set the config, the model file won't be read again. 我不能只设置配置,不会再次读取模型文件。

Please advise. 请指教。

The standard way of achieving a conditional callback is to pass a symbol or proc to :if : 实现条件回调的标准方法是将符号或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

This format could also reference a global configuration setting on Rails.configuration 此格式还可以引用Rails.configuration上的全局配置设置。

after_update :refresh_cache, :if => :cache_available?

def cache_available?
  Rails.configuration.custom_cache.present?
end

This would allow the behavior of the application to change without having to restart the server or remove a constant and reload the file. 这将允许更改应用程序的行为,而不必重新启动服务器或删除常量并重新加载文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM