[Ruby on Rails (RoR)] Use ActiveSupport::Deprecation for deprecation messages in Rails
ActiveSupport::Deprecation
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.
Usages
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.
1 | def process_widget |
Then, in your application logs (or even better, your test suite’s output), you’ll see:
1 | 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 ActiveSupport::Deprecation.disallowed_warnings
The optional 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.
1 | ActiveSupport::Deprecation.disallowed_behavior = :raise |
silence(&block)
Silence deprecation warnings within the block.
1 | ActiveSupport::Deprecation.warn('something broke!') |
silenced()
1 | ActiveSupport::Deprecation.silenced |
warn(message = nil, callstack = nil)
Outputs a deprecation warning to the output configured by ActiveSupport::Deprecation.behavior
.
1 | ActiveSupport::Deprecation.warn('something broke!') |
behavior=(behavior)
Sets the behavior to the specified value. Can be a single value, array, or an object that responds to call.
Available behaviors:
-
raise
Raise ActiveSupport::DeprecationException.
-
stderr
Log all deprecation warnings to $stderr.
-
log
Log all deprecation warnings to Rails.logger.
-
notify
Use ActiveSupport::Notifications to notify deprecation.rails.
-
silence
Do nothing.
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.
1 | ActiveSupport::Deprecation.behavior = :stderr |