MxyL MxyL - 6 months ago 11
Ruby Question

Ruby: check if method is defined before aliasing


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?

Answer

what about

if Test.method_defined? :my_print
    alias_method :old_print, :my_print
end