Ruby: check if method is set before smoothing

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. Then I decided to add some more, but I decided to make an alias.

But this suggests that my_print is already defined. Is there a short and easy way to check if a method to smooth a method is already defined?

+5
source share
4 answers

What about

if Test.method_defined? :my_print
    alias_method :old_print, :my_print
end
+4
source

since "my_print" is not a class method, but an instance method, you should:

if Mod.instance_methods.include? "my_print"
  alias_method :old_print, :my_print
end
+2
source

if method(:my_print) alias_method :old_print, :my_print end

0

defined?.

defined?, , /:

alias_method( :old_print, :my_print ) if defined?( my_print )
0

All Articles