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.
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:
The deprecation warning clearly marks where in your application you’re still using outdated code. If you don’t see the deprecation in your test output, and you’re confident in your test coverage, then it’s safe to remove the outdated code!
Why deprecate code when you could, you know, just fix it in the first place? Asking a few questions can help make that decision:
The longer it’ll take to stop using the deprecated code, or the more people who need to be aware of it, the more beneficial an explicit deprecation warning will be.
And personally, I like deprecation warnings because they’re too noisy for me to ignore too long, and they’re coupled to to code itself rather than something like Jira or Trello. Like any tool, though, it’s up to you and your team to decide whether to use them in your code.
I hope you found this small tip helpful. Thanks as always for reading!
If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.
Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.