Extending a class

Hi All

I’m trying to add methods to a class like:

class Person
def refresh
p “refresh”
end
def dup
P “DUP”
end

TIMED_M = [:refresh, :dup]
TIMED_M.each do |method|
p method
alias_method :"#{method}_without_timing", method

define_method :"{#method}_with_timing" do
  p "timing"
  start_time = Time.now.to_f
  returning(self.send(:"#{method}_without_timing")) do
    end_time = Time.now.to_f
    puts "#{method}: #{"%.3f" % (end_time - start_time)} s."
  end
end

end
end

class << Person
def start_trace
TIMED_M.each do |method|
p “x”
alias_method method, :"#{method}_with_timing"
end
end
end
p = Person.new
p.refresh
Person.start_trace
p.refresh

For some unknown reason I get the following error:
:refresh
:dup
“refresh”
./t2.rb:31:in `start_trace’: uninitialized constant Class::TIMED_METHODS
(NameError)
from ./t2.rb:39

Any suggestions why I get this error ?

thnx a lot
LuCa

Hi –

On Mon, 23 Jun 2008, Luca S. wrote:

end
end_time = Time.now.to_f
alias_method method, :"#{method}_with_timing"
:dup
“refresh”
./t2.rb:31:in `start_trace’: uninitialized constant Class::TIMED_METHODS
(NameError)
from ./t2.rb:39

Any suggestions why I get this error ?

Here’s a boiled-down version:

irb(main):001:0> class C; X = 1; end
=> 1
irb(main):002:0> class << C; X; end
NameError: uninitialized constant Class::X

The reason is that there’s no constant X in the singleton class of C.

I also suspect that what’s above is not actually cut-and-pasted, since
you don’t actually use “TIMED_METHODS” anywhere :slight_smile:

David

David A. Black wrote:

Hi –

On Mon, 23 Jun 2008, Luca S. wrote:

end
end_time = Time.now.to_f
alias_method method, :"#{method}_with_timing"
:dup
“refresh”
./t2.rb:31:in `start_trace’: uninitialized constant Class::TIMED_METHODS
(NameError)
from ./t2.rb:39

Any suggestions why I get this error ?

Here’s a boiled-down version:

irb(main):001:0> class C; X = 1; end
=> 1
irb(main):002:0> class << C; X; end
NameError: uninitialized constant Class::X

The reason is that there’s no constant X in the singleton class of C.

I also suspect that what’s above is not actually cut-and-pasted, since
you don’t actually use “TIMED_METHODS” anywhere :slight_smile:

David

TIMED_M is used:

class << Person
def start_trace
TIMED_M.each do |method|
p “x”
alias_method method, :"#{method}_with_timing"
end
end

Here ‘method’ is aliased using TIMED_M