Rename a method in Ruby
Recently I had a problem with a module that overrode the stub
method with something that was not compatible with RSpec's stub
. I still needed the original method in some places so I could not just remove it.
Assuming the following code:
class Animal
def speak
puts "..."
end
end
class Cat < Animal
def speak
puts "Mew..."
end
end
cat = Cat.new
cat.speak # Says "Mew..."
And assuming we want now to be able to access the original speak
method from a Cat
:
class Cat
alias_method :mew, :speak
remove_method :speak # removes Cat#speak, not Animal#speak
end
cat.speak # Says "..."
cat.mew # Says "Mew..."
Written by Kostas Karachalios
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#