Hi,

On Saturday 10 February 2007 20:17, Ben Johnson wrote:
> Does ruby have "hooks". Where I can define, let's say, a method called
> __before that will be called before ANY method call for that class?

maybe this decorator will fit:

require 'blank' # http://pastie.caboo.se/26558

module Decorator
  def self.decorate real_class, &block
    slate = Blank()
    slate.class_eval do
      define_method(:real_class) { real_class }
      def initialize
        @_object = real_class.new
      end
      def method_missing meth, *args, &block
        @_object.send meth, *args, &block
      end
    end
    slate.class_eval &block
    slate
  end
end

module Kernel
  def Decorate klass, &block
    Decorator.decorate klass, &block
  end
end

class A
  def a; 'a' end
end

with_before_hook = Proc.new {
  protected
  def before_hook meth, *args, &block
    STDOUT.puts "before #{meth}: " << "%s %s" % [args.inspect, block.inspect]
  end
  def method_missing meth, *args, &block
    before_hook meth, *args, &block
    @_object.send meth, *args, &block
  end
}

B = Decorate A, &with_before_hook

>> a = B.new
before inspect: [] nil
=> #<A:0xb7b8b05c>

>> a.class
before class: [] nil
=> A

>> a.methods
before methods: [] nil
=> ["enum_for", "inspect", "send", "taguri.....


but maybe this module is too general for this specific purpouse, but it can 
also be adapted by adding singleton class methods like self.before() and 
self.after() in the initialize, and arrange them to automatically replace 
method_missing with an "hooked" one. or hooks can be explicitely coded into 
the main method_missing.. you choose.

:)
-- 
pub 1024D/8D2787EF  723C 7CA3 3C19 2ACE  6E20 9CC1 9956 EB3C 8D27 87EF