There's a crazy idea out there that monkey-patching is bad. alias_method_chain is perhaps the worst offender. It allows you to easily decorate an object with behavior at runtime. The problem occurs when maintaining code that is all alias_method_chain'ed out - such as ActiveRecord::Base and the gazillion plugins that monkey patch it. It's tough to figure out what method you're actually aliasing away, and god help you if you rely on ordering.

Some may criticize, but I prefer to Do Cool Shit™

I present to you a deliciously self-referential way to keep your alias_method_chain headaches at bay:

1
2
3
4
5
6
7
8
9
$caller_map = {}
class Module
  def alias_method_chain_with_logging(original, chain)
    $caller_map[self.name.to_sym] ||= []
    $caller_map[self.name.to_sym] << caller.first
    alias_method_chain_without_logging original, chain
  end
  alias_method_chain :alias_method_chain, :logging
end
blog comments powered by Disqus