This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Explicit Deprecation
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
After a bit of a hiatus (due to little reportable action on the source tree), a deprecation tidbit was just committed. What’s this little nugget do? The ActiveSupport library now provides the ability to explicitly state what methods are deprecated – which will pump out a warning message when that method is called. This is a nice way of not breaking your codebase by removing deprecated methods, while still letting others know that they’re marked for future removal.
Here’s how it works – simply include the deprecation module in the class that has a deprecated method (in this example a User model object) – and mark the method symbol as deprecated:
require 'active_support/deprecation'
class User < ActiveRecord::Base
deprecate :permitted?
# The now deprecated method
def permitted?(role)
roles.include?(role)
end
end
# This method will execute as normal - except now there's a warning
# message printed to your log file or to standard out:
User.new.permitted?('ADMIN') #=> false
# "Your application calls User##permitted?, which is now deprecated.
# Please see the API documents at http://api.rubyonrails.org/ for more information."
You can also denote deprecation of methods baseed on runtime conditions as well (useful when a method with certain arguments have been deprecated, but the method as a whole is still valid)
require 'active_support/deprecation'
class User < ActiveRecord::Base
# Single arg method is now deprecated
def to_s(format)
if format
ActiveSupport::Deprecation.issue_warning("to_s with a " +
"format is now deprecated, please use the no-arg call.")
# ...
end
#...
end
end
# This method will execute as normal - except now there's a warning
# message printed to your log file or to standard out:
User.new.to_s(:long) #=> "Ryan William Daigle"
# "to_s with a format is now deprecated, please use the no-arg call."
# Please see the API documents at http://api.rubyonrails.org/ for more information."
# However, this method will not have a deprecation warning:
User.new.to_s #=> "Ryan Daigle"
It may not seem like much – but the ability to warn developers that a method is on the path to deprecation can save a lot of pain by making it more apparent which called methods are deprecated and not relying on developers to do their own homework.