Florian Weber wrote:

> hello!
> 
> im currently working on a aop library for ruby. most of the things like 
> pointcuts and
> joinpoints work fairly well. unfortunately i can not find a elegant 
> solution for something:
> 


Well, I have no idea what aop is, but I showed the following code to a 
friend, and he said it looked like aop. I just wanted something to 
easily add scripting to an application. Add multiple "filters" to the 
arguments or result of any method. I wrote it this evening, so there 
could be some bugs in it. But maybe this will be usefull to you:

class Class
  def add_hook(method)
   self.module_eval("
    alias_method :#{method}_old, :#{method}


    @@pre_#{method} = []
    @@post_#{method} = []

    def #{method}(*args)
     @@pre_#{method}.map {|block| *args = block.call(*args)}
     result = #{method}_old *args
     @@post_#{method}.map {|block| result = block.call(result)}
     result
    end

    def #{name}.add_pre_#{method}(&block)
     @@pre_#{method}.push(block)
    end

    def #{name}.add_post_#{method}(&block)
     @@post_#{method}.push(block)
    end
   ")
  end
end

# Example code
class Hello
  def foobar(a,b,c)
   a + b + c
  end
end


o = Hello.new
puts o.foobar(" a ", " b ", " c ")
Hello.add_hook("foobar")
Hello.add_pre_foobar {|a,b,c| [a," change middle argument ",c]}
Hello.add_post_foobar{|res| res + " add something to result"}
puts o.foobar(" a ", " b ", " c ")
puts o.foobar_old(" a ", " b ", " c ")
Hello.add_pre_foobar {|a,b,c| [a,b,"change last one too"]}
puts o.foobar("1","2","3")