%w(hashrockets spaceships bangbangs)

> non-optimized bits & pieces <

Method Aliasing

Method aliasing is what every budding rubyists should pick up. This is done using Module#alias_method:

1
2
3
4
5
6
7
8
class Thing
  def size; :xl; end
  alias_method :mass, :size
end

thing = Thing.new
thing.size # >> xl
thing.mass # >> xl

To say that it is simple aliasing is abit deceiving. Under the hood, ruby creates a copy of the original method Thing#size, thus, even if you change the original method, the new method Thing#mass still points to the same method. Here’s an extension of the above example:

1
2
3
4
5
6
7
8
class Thing
  # Redefining the original method
  def size; :xxl; end
end

thing = Thing.new
thing.size # >> xxl
thing.mass # >> xl

It is important to note that the last technique isn’t encouraged in proper software engineering, yet it can really be useful when u need a quick hack on somebody’s code, just to patch & get things done.

If u have some time to spare, you should read more abt yehuda’s case against rails’ alias_method_chain .

ruby, tips

Comments