Random Ramblings

If you are new to rails you've probably seen the method alias_method_chain but dont know exactly what it does. Here is simplified example.

require 'rubygems'
require 'active_support'

class Breakfast
  def cereal
    "Lucky Charms"
  end
end

Produces:
irb(main):003:0> Breakfast.new.cereal
=> "Lucky Charms"

Nothing exotic here. Just a breakfast class with one method. Lets bring in alias_method_chain.

For that we will need to have a method to 'alias to'.

module Milk
  
  def self.included(base)
    base.alias_method_chain :cereal, :milk
  end
  
  def cereal_with_milk
    "Milk and #{cereal_without_milk}"
  end
  
end

The previous code does the following:

  1. Creates an alias (think shortcut) to the method 'cereal' with the name 'cereal_without_milk'
  2. Creates another alias for cereal_with_milk with the name 'cereal'
  3. Defines the method cereal_with_milk

Now when we call the method breakfast.cereal our newly created action, 'cereal_with_milk' will be called. The code in action:

irb(main):002:0> Breakfast.send(:include, Milk)
=> Breakfast
irb(main):003:0> Breakfast.new.cereal
=> "Milk and Lucky Charms"

The end result, we have milk with our Lucky Charms.

Download the original Code: alias_method_chain_example.rb

Leave a Reply