lost password?

home
•  xaraya
•  rails +
•  django
•  webdev
•  xamp
•  musings

rss
Tag this page
   

ยป Blogs that link here
last modified: Aug 07, 2008
(first posted: Aug 07, 2008)
(230 Reads)
Permalink

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).

 

 

alias method chain in a module

Posted by: Maurizio on August 08, 2008 01:14 PM
Happy to see you have begun posting again ... :)

#

Post a new comment

: This is not spam

Name :