Best practice to mark deprecated code in Ruby? Best practice to mark deprecated code in Ruby? ruby ruby

Best practice to mark deprecated code in Ruby?


For almost all cases, depending on a library or metaprogramming for a deprecation is overkill. Just add a comment to the rdoc and call the Kernel#warn method. For example:

class Foo  # <b>DEPRECATED:</b> Please use <tt>useful</tt> instead.  def useless    warn "[DEPRECATION] `useless` is deprecated.  Please use `useful` instead."    useful  end  def useful    # ...  endend

If you're using Yard instead of rdoc, your doc comment should look like this:

# @deprecated Please use {#useful} instead

Lastly, if you adhere to tomdoc, make your comment look like this:

# Deprecated: Please use `useful` instead

Deprecated: Indicates that the method is deprecated and will be removed in a future version. You SHOULD use this to document methods that were Public but will be removed at the next major version.


Also, don't forget to remove the deprecated method in some future (and properly semver'd) release. Don't make the same mistakes that the Java libraries did.


Ruby Standard Library has a module with the warning logic: https://ruby-doc.org/stdlib/libdoc/rubygems/rdoc/Gem/Deprecate.html. I tend to prefer it to maintain my deprecation messages in a "standard" way:

# my_file.rbclass MyFile  extend Gem::Deprecate  def no_more    close  end  deprecate :no_more, :close, 2015, 5  def close    # new logic here  endendMyFile.new.no_more# => NOTE: MyFile#no_more is deprecated; use close instead. It will be removed on or after 2015-05-01.# => MyFile#no_more called from my_file.rb:16.

Note that with this approach you will gain for free information about where the call took place.


Using ActiveSupport:

class Player < ActiveRecord::Base  def to_s    ActiveSupport::Deprecation.warn('Use presenter instead')    partner_uid  endend

Warnings are turned off in production environment by default