Support passing a category to Warning.warn

This change adds a `category` kwarg to make it easier to monkey patch
`Warning.warn`. Warnings already have a category, but that warning isn't
exposed. This implements a way to get the category so that warnings with
a specific category, like deprecated, can be treated differently than
other warnings in an application.

The change here does an arity check on the method to support backwards
compatibility for applications that may already have a warning monkey
patch.

For our usecase we want to `raise` for deprecation warnings in order to
get the behavior for the next Ruby version. For example, now that we
fixed all our warnings and deployed Ruby 2.7 to production, we want to
be able to have deprecation warnings behave like they would in 3.0: raise
an error. For other warnings, like uninialized constants, that behavior
won't be removed from Ruby in the next version, so we don't need to
raise errors.

Co-authored-by: Aaron Patterson <tenderlove@ruby-lang.org>
This commit is contained in:
eileencodes 2020-08-06 13:25:11 -04:00 committed by Jeremy Evans
parent de10a1f358
commit 6e8ec9ab6d
Notes: git 2020-09-02 08:16:38 +09:00
3 changed files with 54 additions and 8 deletions

View file

@ -915,7 +915,7 @@ $stderr = $stdout; raise "\x82\xa0"') do |outs, errs, status|
end
end
def capture_warning_warn
def capture_warning_warn(category: false)
verbose = $VERBOSE
deprecated = Warning[:deprecated]
warning = []
@ -924,8 +924,14 @@ $stderr = $stdout; raise "\x82\xa0"') do |outs, errs, status|
alias_method :warn2, :warn
remove_method :warn
define_method(:warn) do |str|
warning << str
if category
define_method(:warn) do |str, **kw|
warning << [str, kw[:category]]
end
else
define_method(:warn) do |str|
warning << str
end
end
end
@ -954,6 +960,18 @@ $stderr = $stdout; raise "\x82\xa0"') do |outs, errs, status|
assert_equal(["\n"], capture_warning_warn {warn ""})
end
def test_warn_backwards_compatibility
warning = capture_warning_warn { Object.new.tainted? }
assert_match(/deprecated/, warning[0])
end
def test_warn_category
warning = capture_warning_warn(category: true) { Object.new.tainted? }
assert_equal :deprecated, warning[0][1]
end
def test_kernel_warn_uplevel
warning = capture_warning_warn {warn("test warning", uplevel: 0)}
assert_equal("#{__FILE__}:#{__LINE__-1}: warning: test warning\n", warning[0])