Deprecating methods in ruby
Ruby best-practices
When time comes, code is changing — and also some methods my go away or will be simply renamed.
class Foo
def old_method
# ...
end
def the_new_thing
# ..
end
end
But how to deprecate them efficiently in Ruby? I suggest to deprecate it in the code documentation and with a warning when executing the code.
I prefer to use Yard for code documentation. Yard provdes the @deprecated
tag for this.
class Foo
# Does some stuff the old fashioned way.
#
# @deprecated Please use {#the_new_thing} instead
def old_method
# ...
end
# Does some stuff the cool way.
def the_new_thing
# ..
end
end
See the YARD Tag documentation o @deprecated
for more information.
Second, it would be great to get a warning when executing the deprecated method. This enables a good developer to monitor his console — or in operations his log files for any deprecation messages which he should be aware of.
Ruby provides with the Gem::Deprecate
module a standardized way to do this.
class Foo
extend Gem::Deprecate
# Does some stuff the old fashioned way.
#
# @deprecated Please use {#the_new_thing} instead
def old_method
# ...
end
deprecate :old_method, :the_new_thing, 2016, 4
# Does some stuff the cool way.
def the_new_thing
# ..
end
end
When the method Foo.new.old_method
is then called, the following warning will be printed:
NOTE: Foo#old_method is deprecated; use the_new_thing instead. It will be removed on or after 2016–04–01.
Foo#old_method called from (pry):17.
This message tells the developer how the replacement is called, when he can expect that the method will be removed and where it was called exactly (in this case, line 17 of a REPL session). Especially that it tells where it was called exactly is really useful when updating the code.
See the code at https://gist.github.com/tmaier/cea248cee04eb685e845.