I would like to count method calls of new methods defined in a class. To do this, I redefine each newly defined method using method_added
hook. Inside it, I use define_methodand increment the value of a class variable
@@test_count`.
Base class:
class Unit
@new_method = true
@@test_count = 0
def self.test_count
puts @@test_count
end
def self.method_added(name)
old_method = instance_method(name)
if @new_method
@new_method = false
define_method(name) do |*args, &block|
@@test_count += 1
old_method.call(*args, &block)
end
@new_method = true
end
end
end
Subclass with newly defined methods:
class Test < Unit
def test_assertion
puts true
end
end
When I call a new method, @@test_count
is still 0:
Test.new.test_assertion
Unit.test_count
true
0
Why @@test_count
value isn't changed?