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

defrun(job)puts'executing job'end

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.

classAwesomedefrun(*args)# do some work...
endendawesome=Awesome.newawesome.run

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.

classAwesomedefexecute(*args)# do some work...
endendawesome=Awesome.newawesome.run

This code will result in an exception:

NoMethodError: undefined method `run' for main:Object

To remedy this we use alias to ensure nothing breaks.

classAwesomedefexecute(*args)# do some work...
endalias:run:executeendawesome=Awesome.newawesome.run

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.

Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.