rails
(45,652 views)

alias method chain in a module

There's a number of postings that explain how to use alias_method_chain, but it wasn't clear how to use it in a module.

alias_method_chain is a neat little method that lets you cleanly override a core method in Rails. But I ran into syntax problems using it in a module. Here's the solution.

Given:

file: models/foo.rb

class Foo < ActiveRecord::Base
  include FooBar
end


file: lib/foo_bar.rb

module FooBar
  module ClassMethods
    def find_with_bar( *args ) 
      find_without_bar( *args )
      #...or whatever 
    end
  end
  
  def self.included(base)
    base.class_eval do
      extend ClassMethods
      class << self
        alias_method_chain :find, :bar
      end
    end
  end
  
end

The alias_method_chain will alias the original find to find_without_bar, and will alias find_with_bar to find.

The self.included method is called when the module is included in the Foo class. It extends the class methods with those defined in module ClassMethods. And then it does the alias_method_chain, on the Foo class (class << self).

 

 

Comments

by Maurizio on Aug 08, 2008

>>

Happy to see you have begun posting again ... :)

by Anonymous on Sep 04, 2008

>>

exactly what i need! thanks for the great post. - sandeep

by Foliosus on Sep 09, 2008

Saved my bacon

Thanks for this -- it's exactly what I was looking for. :)

by korinthe on Mar 19, 2010

and for instance methods...

  base.class_eval do
    extend ClassMethods
    alias_method_chain :link_to, :authentication
  end

(leaving off the class << self ... end)

by korinthe on Mar 19, 2010

formatting lost

And for instance methods...

  base.class_eval do&lt;br/&gt;
    extend ClassMethods&lt;br/&gt;
    alias_method_chain :link_to, :authentication&lt;br/&gt;
  end&lt;br/&gt;

(Leaving off the class << self ... end)

New Comment

markdown formatting permitted