Aliasing overridden methods in Ruby
Wednesday, February 16, 2011 at 7:24PM So, one of the great things about Ruby is that you can open up a class and override methods. The problem is when you need to call the old method. The first thing you can do is use the alias method to alias the old method to a new name and call it from the new method.
class Post
alias :old_save, :save
def save
puts "Saving post"
old_save
end
end
While this works, it can cause problems when working with larger codebases. Someone could define a method called old_save, or use it as their alias name, overwriting your work. A much better idea is to steal the method from the class, save it in a variable, bind it to the current instance then call it using Ruby's call method.
class Post
old_save = self.instance_method(:save)
define_method(:save) do
puts "Saving post"
old_save.bind(self).call
end
end
The above version means that the old_save method won't be left around as a method, it's a private variable in the scope of that class. We have to use define_method to define the method as the old_save method is only available in the scope of the class. We could save it as an instance variable, but this would just cause the same issues.


