Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: check if method is defined before aliasing

Tags:

ruby

class Test

  def my_print
    p "Print something"
  end
end

class Test

  alias_method :old_print, :my_print
  def my_print
    old_print
    p "Print some more"
  end
end

My original Test class is at the top. I then decided to add some more to it, but I decided to alias.

But that assumes my_print is already defined. Is there a short and simple way to check whether a method I'm aliasing is already defined?

like image 538
MxLDevs Avatar asked May 20 '12 21:05

MxLDevs


1 Answers

what about

if Test.method_defined? :my_print
    alias_method :old_print, :my_print
end
like image 142
Mauricio Avatar answered Oct 07 '22 22:10

Mauricio