[Ruby on Rails (RoR)] Use ActiveSupport::Deprecation for deprecation messages in Rails
When upgrading a Rails application to a newer version of the framework, you’ll often see deprecation warnings pop up in your application logs and test suite output. Deprecation warnings give you time to fix an issue before it becomes an outright error. Good deprecation warnings also give you a hint on where and how to address them.
Rails makes it pretty simple to add good deprecation warnings to your actual application code, too. Let’s first look at how to do this, then talk for a moment about when it might be a good idea.
Adding the deprecation
Inside the method you want to deprecate, use ActiveSupport::Deprecation.warn, with a string to describe what’s been deprecated, and how developers should work around the deprecation going forward.
Then, in your application logs (or even better, your test suite’s output), you’ll see:
DEPRECATION WARNING: #process_widget is deprecated. Use
Instance Public methods
allow(allowed_warnings = :all, if: true, &block)Link
Allow previously disallowed deprecation warnings within the block. allowed_warnings can be an array containing strings, symbols, or regular expressions. (Symbols are treated as strings). These are compared against the text of deprecation warning messages generated within the block. Matching warnings will be exempt from the rules set by
if: argument accepts a truthy/falsy value or an object that responds to
.call. If truthy, then matching warnings will be allowed. If falsey then the method yields to the block without allowing the warning.
ActiveSupport::Deprecation.disallowed_behavior = :raise
Silence deprecation warnings within the block.
warn(message = nil, callstack = nil)
Outputs a deprecation warning to the output configured by
Sets the behavior to the specified value. Can be a single value, array, or an object that responds to call.
Log all deprecation warnings to $stderr.
Log all deprecation warnings to Rails.logger.
Use ActiveSupport::Notifications to notify deprecation.rails.
Setting behaviors only affects deprecations that happen after boot time. Deprecation warnings raised by gems are not affected by this setting because they happen before Rails boots up.
ActiveSupport::Deprecation.behavior = :stderr
 ActiveSupport::Deprecation::Reporting - https://api.rubyonrails.org/classes/ActiveSupport/Deprecation/Reporting.html
 ActiveSupport::Deprecation::Behavior - https://api.rubyonrails.org/classes/ActiveSupport/Deprecation/Behavior.html
 Use Active Support in Rails for deprecation messages - Andy Croll - https://andycroll.com/ruby/use-a-deprecation-message/
 Deprecating code in a Rails application | Everyday Rails - https://everydayrails.com/2021/07/31/rails-custom-deprecation-warnings.html