Ruby - Aliasing Methods, Just Because You Can
Ruby gives you a way to alias a method, what this means is you can call the method Foo and alias it as Bar and when a user of the class calls Bar the call is proxied to Foo. My libraries and classes evolve over time, being able to alias’ methods allow you to keep method names around as you deprecate certain functionality
So should method be renamed from run to execute we have a way to ensure that any other calling code won’t break. Let’s look at a practical example.
Now if we changed the run method to execute without using alias and keeping all the code as it stands we would break any callers.
This code will result in an exception:
NoMethodError: undefined method `run' for main:Object
To remedy this we use alias to ensure nothing breaks.
Now the code works again. One important thing to remember here is to make sure the alias call is made after the declaration of the method, failing to do so will result in a ‘NoMethodError.’
What a great way to ensure backward compatibility, but also a way to migrate use of a library over time without breaking dependent code.