Jamie Lawrence

Add Deprecation Warnings to your Rails App

You’ve probably seen deprecation warnings in Rails, especially if you made the jump to 5.2 recently, but did you know you can use them in your own app?

I suspected so but hadn’t done it before. Here’s a Rails model with a url attribute.

# == Schema Information
#
# Table name: memberships
#
#  id                     :integer          not null, primary key
# ...snip...
#  url                    :string           indexed
#
class Membership < ApplicationRecord

  # ...snip...
  def url=(url)
    super(url.try(:downcase))
  end
end

That url attribute is going away to be replaced by a different mechanism based around a path attribute. url is used in lots of places, throughout the app, and it’s a pretty hard attribute to search for.

Now, in this instance, I can do something like

class Membership < ApplicationRecord
  alias url= path=
end

to forward all calls to url= to the path= method.

The downside is the Membership#url will continue to proliferate through the codebase. You’ve deferred the problem but you haven’t solved it.

Enter deprecate 👋

It’s actually pretty easy to make use of the Rails deprecation functionality.

class Membership < ApplicationRecord
  def url=(url)
    super(url.try(:downcase))
  end

  deprecate :url=
end
membership.url = 'test'
# DEPRECATION WARNING: url= is deprecated and will be removed from Rails 6.0  (called from block (4 levels) in <main> at /Users/jamie/projects/podia/spec/models/membership_spec.rb:93

The method still works but a deprecation warning is printed. Except… it talks about Rails 6.0 which is not our app.

Let’s customise!

We can pass a custom deprecator to the deprecate method

class Membership < ApplicationRecord
  def url=(url)
    super(url.try(:downcase))
  end

  custom_deprecator = ActiveSupport::Deprecation.new('my-future-cleanup branch', 'Podia')
  deprecate :url, :url=, deprecator: custom_deprecator
end
membership.url = 'test'
# DEPRECATION WARNING: url= is deprecated and will be removed from Podia my-future-cleanup branch (called from block (4 levels) in <main> at /Users/jamie/projects/podia/spec/models/membership_spec.rb:93