Prior method definition

This feels cleaner than the alias_method + redef. method trick, and I
haven’t found anything similar in the archives.

It still suffers from the problem exposed in [ruby-talk:75334]. In
addition, blocks cannot be propagated but it will be possible once
[ruby-talk:90671] is implemented (of course, by then we’ll have real
advices, but still :wink:

batsman@tux-chan:~/src$ cat aop2.rb

class Module
def def_advice(meth, &block)
prev = self.instance_method(meth)
define_method(meth) do |*a|
block.call prev.bind(self), *a
end
end

def def_preadvice(meth, &block)
    prev = self.instance_method(meth)
    define_method(meth) do |*a|
        block.call(*a)
        prev.bind(self).call(*a)
    end
end

def def_postadvice(meth, &block)
    prev = self.instance_method(meth)
    define_method(meth) do |*a|
        prev.bind(self).call(*a)
        block.call(*a)
    end
end

end

class A
def foo(*a)
puts "A#foo #{a.inspect}"
end
end
a = A.new
a.foo

class A
def_advice(:foo) do |prev, *a|
puts "before"
prev[*a]
puts "after"
end
end

puts "–"
a.foo

class A
def_preadvice(:foo) { puts “pre 1” }
def_postadvice(:foo) { puts “post 1”}
def_preadvice(:foo) { puts “pre 2” }
end

puts "–"
a.foo
batsman@tux-chan:~/src$ ruby ao
aop.rb aop2.rb
batsman@tux-chan:~/src$ ruby aop2.rb
A#foo []

···


before
A#foo []
after

pre 2
pre 1
before
A#foo []
after
post 1


Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Beeping is cute, if you are in the office :wink:
– Alan Cox