I explain alias_method_chain and save the day

by janedotx7


Hello. “alias_method_chain” is a Rails-ism that keeps confusing me.
The implementation  looks something like this: 

def alias_method_chain(target, feature)
  alias_method “#{target}_without_#{feature}”, target
  alias_method target, “#{target}_with_#{feature}”

I found this weird, but diagramming the method
declarations and what was supposed to happen was very helpful, and now
I get it.

In the diagram, each word outside of a box indicates the method name,
and the word within the box indicates a method implementation. Imagine
that Ruby has a set of boxes that each hold a method implementation,
and each box is labeled with the method’s name. You can change the
method name, but not change the content of the box, and you’ll still
have a method that does the exact same thing–just named differently.

Every time you use “alias_method,” you can think of it as Ruby copying
the box and putting a different method name on it. The previous copy
of the box with the old name still exists. You can redefine a new box
with the old name and it won’t affect the new copy with the different

So in the top part of the diagram, you start with the methods
“feature” and “target.” After you use alias_method_chain on them,
you’ll need to define a method named “target_with_feature” so there’s
a box of “target_with_feature” code to copy to the “target” method

The resulting four boxes in the bottom part of the diagram represent
all the new boxes with their names after we call alias_method_chain,
and define “target_without_feature.”

Pardon the ASCII art, but the Gimp is still downloading.