New in Rails: Module#alias_method_chain

Though not an outward facing feature, changeset 4276 introduces a nice method to DRY up and encapsulate the common pattern of aliasing a method so that you can build behavior on top of it.

All over the internals of Rails you’ll find code like this in a module:


  module Layout #:nodoc:
    def self.included(base)
      base.extend(ClassMethods)
      base.class_eval do
        alias_method :render_with_no_layout, :render
        alias_method :render, :render_with_a_layout

  1. … etc

This makes it so that when the module is included into the base class, it adds behavior onto some method in that class without the method having to be aware of the fact that it’s being enhanced. In this case, the render method of ActionController::Base is enhanced to wrap its output in a layout.

The new Module#alias_method_chain wraps up this pattern into a single method call. The above example, once refactored to use Module#alias_method_chain, would simply be:


alias_method_chain :render, :layout

This will be used to refactor quite a bit of Rails internals which may not be of immediate relevance to what you do, but it serves as a nice example of the mechanisms Ruby provides for software organization. Small victories.

blog comments powered by Disqus