如何有选择地静音Rails 3弃用警告?

Pas*_*cke 10 configuration unit-testing ruby-on-rails shoulda deprecated

我正在升级Rails 2到Rails 3应用程序(代码不是由我编写的).(经过良好测试的代码)使用shoulda和Test :: Unit,并广泛使用宏should_create和should_change.

我从这个讨论中了解到,shoulda维护者希望摆脱这两种方法,但使用Test :: Unit的人并不觉得有必要(不确定我是否正在抓住整个讨论).

Anaway,有没有办法选择性地转换指定宏的弃用警告?我已经从这篇文章中了解到,您可以通过设置完全关闭Rake测试输出中的弃用警告:

ActiveSupport::Deprecation.silenced = true
Run Code Online (Sandbox Code Playgroud)

在您的测试环境文件中,我也知道您可以将特定的代码块放在一个块中以使它们静音:

ActiveSupport::Deprecation.silence do
# no warnings for any use of deprecated methods here
end
Run Code Online (Sandbox Code Playgroud)

后者是一个选项,但需要我遍历所有测试并将should_create宏包含在这样的块中.所以我想知道有一种方法可以完全消除特定宏的警告,只需一个配置设置?

tim*_*les 6

旧问题 - 但如果你有新的折旧,你有选择地忽略:

ActiveSupport::Deprecation.behavior = lambda do |msg, stack| 
  unless /LIBRARY_NAME/ =~ msg
    ActiveSupport::Deprecation::DEFAULT_BEHAVIORS[:stderr].call(msg,stack) # whichever handlers you want - this is the default
  end
end
Run Code Online (Sandbox Code Playgroud)

这适用于ActiveSupport 3.


Pas*_*cke 3

事实上,我仍然收到了来自我安装的插件或 gem 中的代码的许多其他弃用警告。为了避免大多数情况,我覆盖了 test_helper.rb 中的 Deprecation::warn 方法。因此,不要使用以前的代码,而是使用:

module ActiveSupport
  module Deprecation
    class << self
      def warn(message = nil, callstack = caller)
        # modif pvh the following lines make sure no deprecation warnings are sent 
        # for code that is
        # not by my but in some gem or plugin...
        return if silenced  || callstack.grep(/myrailsappname/).blank?
        # return if silenced 
        deprecation_message(callstack, message).tap do |m|
          behavior.each { |b| b.call(m, callstack) }
        end
      end
    end
  end
end  
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您需要将 myrailsappname 替换为应用程序的名称(它所在的文件夹的名称)。可能有一种更通用的方法来获取该名称,但我现在找不到它。