title: Ruby: How to hook onto class methods
body: <p>From: <a href="http://cheind.blogspot.com/2008/12/method-hooks-in-ruby.html" rel="nofollow">http://cheind.blogspot.com/2008/12/method-hooks-in-ruby.html</a></p>
  
  <p>I have</p>
  
  <pre><code># Contains methods to hook method calls
  module FollowingHook
  
    module ClassMethods
  
      private
  
      # Hook the provided instance methods so that the block 
      # is executed directly after the specified methods have 
      # been invoked.
      #
      def following(*syms, &amp;block)
        syms.each do |sym| # For each symbol
          str_id = "__#{sym}__hooked__"
          unless private_instance_methods.include?(str_id)
            alias_method str_id, sym        # Backup original 
                                            # method
            private str_id                  # Make backup private
            define_method sym do |*args|    # Replace method
              ret = __send__ str_id, *args  # Invoke backup
              block.call(self,              # Invoke hook
                :method =&gt; sym, 
                :args =&gt; args,
                :return =&gt; ret
              )
              ret # Forward return value of method
            end
          end
        end
      end
    end
  
    # On inclusion, we extend the receiver by 
    # the defined class-methods. This is an ruby 
    # idiom for defining class methods within a module.
    def FollowingHook.included(base)
      base.extend(ClassMethods)
    end
  end
  </code></pre>
  
  <p>Then I have a class like so:</p>
  
  <pre><code>class User
    def self.get
     #class method
    end
    def name
     #instance method
    end
  end
  </code></pre>
  
  <p>In another location/file I reopen the User class and hook into it</p>
  
  <pre><code>class User
    include FollowingHooks # include the hook module
    following :name do |receiver, args|
     #do something. This works!!
    end
    following :get do |reciever, args|
     #do something. THIS DOESNT WORK
     # Which is to be expected looking at the FollowingHooks module definition.
    end
  end
  </code></pre>
  
  <p>Hooking into any instance methods works. However trying to hook into class methods does nothing, which I get, because the FollowingHooks module doesn't implement it. How would I implement hooks for class methods? I am totally clueless. </p>