On Tue, Sep 28, 2004 at 01:28:47AM +0900, trans.  (T. Onoma) wrote:
> > Could you just use super?
> >
> >   class A
> >     def a; puts "in a"; end
> >   end
> >   class B < A
> >     def a
> >       puts "before"
> >       super
> >       puts "after"
> >     end
> >   end
> 
> The idea is to submethod multiple methods in one fell-swoop. Hence:
> 
>   if /^a/ =~ meth.to_s
> 
> If you have any ideas on other ways to do this, I would love to hear them.

batsman@tux-chan:/tmp$ cat gdfgrre.rb

module Magic
    def wrap_method(*names, &block)
        names.each do |name|
            old = instance_method(name)
            define_method(name) do |*a|  # |*a, &b|  on 1.9
                block.call(name, old.bind(self), *a) # &b on 1.9
            end
        end
    end
end

class A
    def foo; puts "A#foo" end
    def bar; puts "A#bar" end
end

class B < A
    extend Magic

    wrap_method(:foo, :bar) do |meth, old|
        puts "pre"
        puts "About to call #{meth}"
        if meth.to_s == "foo"
            puts "special action for foo!"
        end
        old.call
        puts "post"
    end
end

b = B.new
b.foo
b.bar
batsman@tux-chan:/tmp$ ruby gdfgrre.rb
pre
About to call foo
special action for foo!
A#foo
post
pre
About to call bar
A#bar
post

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