Can't find that Rails Method? (alias_method_chain)
I've been digging through the core more and more. One thing that still throws me off once in a while are method declarations that I can't seem to find. Naturally, I first do a search for the method name in a bunch of files. When it doesn't show up, I become frustrated because even if it was aliased, it should still come up in search. Well, if that's the case, look no further than a call to #alias_method_chain(usually). Even though I was aware of this method(it's nothing new), it still throws me off. I just need to remember anytime I see "with" or "without" in the method name, I should probably search for a call to #alias_method_chain.
For those of you not aware of what it is, here is the code(aliasing.rb):
1 2 3 4 5 6 7 8 |
def alias_method_chain(target, feature) # Strip out punctuation on predicates or bang methods since # e.g. target?_without_feature is not a valid method name. aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 yield(aliased_target, punctuation) if block_given? alias_method "#{aliased_target}_without_#{feature}#{punctuation}", target alias_method target, "#{aliased_target}_with_#{feature}#{punctuation}" end |
It is used to DRY up the common aliasing pattern of:
1 2 |
alias_method :foo_without_feature, :foo alias_method :foo, :foo_with_feature |
This is used a lot in the Rails core. It is nice, but when you're not aware of it, it can certainly wear on you when trying to understand some code. I know it's a method that has been talked about plenty, but it's one of those things that is hard to search for when you're actually trying to solve the mystery it created.
