prior method definition

  • Thread starter Mauricio Fernández
  • Start date
M

Mauricio Fernández

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 ;)

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 ;)
-- Alan Cox
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top