Ruby - Aliasing Methods, Just Because You Can

September 17, 2014

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

def run(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.

class Awesome

    def run(*args)
        # do some work...
    end

end

awesome = Awesome.new
awesome.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.

class Awesome

    def execute(*args)
        # do some work...
    end

end

awesome = Awesome.new
awesome.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.

class Awesome

    def execute(*args)
        # do some work...
    end

    alias :run :execute

end

awesome = Awesome.new
awesome.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.

comments powered by Disqus