metaduck
16Out/091

How to alias_method_chain a class method on Rails

Sometimes, when building a plugin, you have to extend Rails behaviour using alias_method_chain.

So you do, on the included module:

...
    def self.included(base)
      base.send :include  InstanceMethods
      base.class_eval do
        alias_method_chain :method_i_want_to_extend, :my_feature
      end
    end

    module InstanceMethods
     def method_i_want_to_extend_with_my_feature(args)
       (do something or not...)
       method_i_want_to_extend_without_my_feature(args)
       (do something or not...)
     end
    end
...

What if the method you are extending is a class method?

Simple, just use the singleton class:

...
    def self.included(base)
      base.extend ClassMethods
      base.class_eval do
        class << self
          alias_method_chain :method_i_want_to_extend, :my_feature
        end
      end
    end

    module ClassMethods
     def method_i_want_to_extend_with_my_feature(args)
       (do something or not...)
       method_i_want_to_extend_without_my_feature(args)
       (do something or not...)
     end
    end
...

About Pedro Teixeira

Pedro Teixeira is a former Enterprise Java Beans technical project manager for Clarity Europe (BES Tech Ventures). On 2004 he founded a services company ( http://berro.pt ), focused on the tourism industry throughout 2005-2008, briefly worked for http://www.expedita.com, shifted to product development on 2007, rebuilt http://netmadeira.com on 2009 for ZON Madeira. On early 2010 he started freelance work for Avallain, an e-Learning company strongly focused on delivering multi-media learning content and learning community expericences.
Comments (1) Trackbacks (0)

Leave a comment


No trackbacks yet.