Reputation: 19506
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?
Upvotes: 6
Views: 2090
Reputation: 47481
defined?
Method.You can use the defined?
method to see if a method has already been defined within the current context/scope:
alias_method( :old_print, :my_print ) if defined?( my_print )
Upvotes: 0
Reputation: 803
if method(:my_print)
alias_method :old_print, :my_print
end
Upvotes: 0
Reputation: 21569
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
Upvotes: 3
Reputation: 5853
what about
if Test.method_defined? :my_print
alias_method :old_print, :my_print
end
Upvotes: 4