Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Custom Deprecation Notices

Tags:

Is there a way to create custom deprecation notices for methods and/or associations in my application that I plan on removing and want to log their usage? I have a relationship in one of my models that I don't want to use moving forward and plan to refactor the code at a later time. I would like to create a notice in my development log every time that method is called.

I have seen deprecation notices in Ruby/Rails when using certain methods, and figure there has to be an easy way to do this.

Something like...

irb(main):001:0> 1.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 3
like image 955
Peter Brown Avatar asked Feb 17 '10 20:02

Peter Brown


4 Answers

In Rails 3 you can use the : "deprecate" method from ActiveSupport:

class Example
  def foo
  end

  deprecate :foo
end

It will create an alias for your method and output a warning with a stack trace. You can also use parts of this functionality directly, e.g:

ActiveSupport::Deprecation.warn("Message")

It will output the stack trace along with the message.

like image 182
Eugene Bolshakov Avatar answered Nov 15 '22 09:11

Eugene Bolshakov


Maybe:

def old_relationship
  warn "[DEPRECATION] old_relationship is deprecated."
  @old_relationship
end

def old_relationship=(object)
  warn "[DEPRECATION] old_relationship is deprecated."
  @old_relationship = object
end

Something along those lines for a relationship.

like image 35
Alan Peabody Avatar answered Nov 15 '22 09:11

Alan Peabody


In the majority of cases, you can just raise a warning and call the new method.

class Example
  # <b>DEPRECATED:</b> Please use <tt>good_method</tt> instead.
  def bad_method
    warn "`bad_method` is deprecated. Use `good_method` instead."
    good_method
  end

  def good_method
    # ...
  end
end

There are libraries or metaprogramming if you need or want to get fancier, but in general that's not a good route to go for something this simple. You should have a pretty good reason to introduce a dependency for something this simple.

like image 34
John Feminella Avatar answered Nov 15 '22 10:11

John Feminella


Adding my 2 cents:

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.

like image 31
facundofarias Avatar answered Nov 15 '22 09:11

facundofarias