2011-02-04 66 views
10

我升级Rails的2至3的Rails应用程序(不是我写的代码)。 的(以及测试的代码)使用早该和测试::单位,并广泛使用的宏should_create和should_change。如何选择性地静音Rails 3弃用警告?

我从this discussion了解到,shoulda维护者想摆脱这两种方法,但使用Test :: Unit的人没有发现它是必要的(不确定我是否理解了整个讨论)。

Anaway,有没有办法能够选择性地指定宏打开废弃警告吗?我已经从this posting知道,你完全可以通过设置关在瑞克测试输出的废弃警告:

ActiveSupport::Deprecation.silenced = true 
在您的测试环境文件

,我也知道,你可以把特定的代码块的块,让他们沉默:

ActiveSupport::Deprecation.silence do 
# no warnings for any use of deprecated methods here 
end 

后者是一种选择,而是需要我去了所有的测试和封闭should_create宏在这样一个块。所以我想知道有一种方法可以完全消除一个配置设置的特定宏的警告?

回答

3

其实我还是老样子有很多从其他代码废弃警告,那是在插件或我已经安装了宝石。为了避免大部分情况,我重写了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 

顺便说一句,你需要与你的应用程序的名称(它驻留在该文件夹的名称),以取代myrailsappname。可能有更通用的方式来获得该名称,但我现在找不到它。

0

我想我已经发现了一个解决方案:在测试/ test_helper.rb中我重新打开该模块并改写宏定义具有相同的定义,但弃用警告注释。可能有更优雅的方式来做到这一点,但...

# modif pvh DEPREC 
# reopen the module and silence the deprecation statement to avoid 
# having my results overflown by these deprecation warnings... 
module Shoulda # :nodoc: 
    module Macros 
    def should_create(class_name) 
     ##::ActiveSupport::Deprecation.warn 
     should_change_record_count_of(class_name, 1, 'create') 
    end 
    end 
end 
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 

这是ActiveSupport 3

+2

仍然可以在ActiveSupport 4中使用。 – 2015-03-10 20:09:49

2

我可以推荐别的选择吗?

module ActiveSupport 
    class Deprecation 
    module Reporting 
     # Mute specific deprecation messages 
     def warn(message = nil, callstack = nil) 
     return if message.match(/Automatic updating of counter caches/) 

     super 
     end 
    end 
    end 
end