prior method definition

Discussion in 'Ruby' started by Mauricio Fernández, Apr 17, 2004.

  1. 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
     
    Mauricio Fernández, Apr 17, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jianli Shen
    Replies:
    1
    Views:
    618
    Victor Bazarov
    Mar 13, 2005
  2. Ark
    Replies:
    1
    Views:
    445
    Chris Torek
    Aug 7, 2004
  3. Jon Slaughter
    Replies:
    4
    Views:
    465
    Jon Slaughter
    Oct 26, 2005
  4. Pierre Yves
    Replies:
    2
    Views:
    512
    Pierre Yves
    Jan 10, 2008
  5. Francis Hwang
    Replies:
    4
    Views:
    134
    Pit Capitain
    Mar 8, 2005
Loading...

Share This Page