Using alias_method before function definition

Hi guys, I'm having problems with using alias_method. When i run this
code, I'm getting undefined method `shout' for class `Person'
(NameError) since I'm using alias_method on a function that is probably
not defined yet. The example would work if I put the profile method
after the method name, but is there a cleaner solution to make this
work? This post (http://www.ruby-forum.com/topic/100587) seem to solve
this problem using "method_added" callback but i hope i could use a
different approach

module SimpleProfiler
  def profile(*methods)
    methods.each do |method|
      send :alias_method, "orig_#{method}", method

      define_method method do |name|
        before = Time.now
        send "orig_#{method}", name
        after = Time.now
        puts sprintf("%s: %.4fs", method, after - before)
      end
    end
  end
end

class Person
  extend SimpleProfiler
  profile :shout

  def shout(name)
    sleep(1)
    puts name
  end
end

p = Person.new
p.shout("reg")

···

--
Posted via http://www.ruby-forum.com/.

Oops, correction:

define_method method do |name|
    before = Time.now
    send "orig_#{method}", name
    after = Time.now
    puts sprintf("%s: %.4fs", method, after - before)
end

should be

define_method method do |*args|
    before = Time.now
    send "orig_#{method}", *args
    after = Time.now
    puts sprintf("%s: %.4fs", method, after - before)
end

···

--
Posted via http://www.ruby-forum.com/.

Reginald Tan wrote in post #1024307:

The example would work if I put the profile method
after the method name, but is there a cleaner solution to make this
work?

I don't think so. The trouble is, alias_method acts on the version of
the method *as it was defined at that time*. So you could define a dummy
method first, and copy it with alias_method, but when you redefine it
the alias would still point to the first one.

  def foo
    puts "Version 1"
  end

  alias :bar :foo

  def foo
    puts "Version 2"
  end

  foo # prints "Version 2"
  bar # prints "Version 1"

HTH,

Brian.

···

--
Posted via http://www.ruby-forum.com/.

hmm, maybe i should use something else other than alias_method. or i'll
probably just stick with method_added callback

···

--
Posted via http://www.ruby-forum.com/.