cgore.comcgore@cgore.commicroblogblogphotosChristianitycryptographyjournalingoutdoorsmy master's thesisprogramming
Thinking Bicycle
Github @cgoreFacebook @cgoreInstagram @christopher.mark.gore

This website is copyright © 1995-2016 Christopher Mark Gore, all rights reserved. The content may not be copied or republished via any means, traditional or electronic, without express written permission of the author.

Chris Gore: Programming: Ruby: Public Aliases of Private Methods

I commonly define a set of related methods that do almost the same task and add an alias to the 'right' one. For example, I might need blocking and non-blocking receive methods for some network tool, but only ever want to publically expose the non-blocking version, using the blocking one just in some weird case for one of the other class methods. Or perhaps there are several different algorithms that I implemented to achieve the same thing, and didn't know which one I really wanted until I implemented all of them and could compare: Algorithm #7 of 12 is the 'good' one, but I don't want to delete the code for the other 11.

How I typically deal with this is by aliasing the 'good' one with a generic method name and only publically exposing that one. But the problem is that Ruby makes the aliased function private as the alias too. We can fix this by explicitly making the alias public after making the real method private. Here is a contrived example:

class A
  def f_good *args
    puts *args

  def f_bad x
    puts x

  def f_worse x
    print "x\n"

  private :f_good, :f_bad, :f_worse
  alias_method :f, :f_good
  public :f

That way I can keep around the other implementations if I want to, and have the good one named appropriately, but I don't have to worry about somebody, myself included, accidentally using one of the 'wrong' ways from some other code.