I was wondering if it’s possible to make it so that if I had something like
class Test
attr_reader :access_times
def initialize
@access_times = 0
end
def get_two
2
end
...
end
t = Test.new
That any access to t would run a particular piece of code before actually running the method?
For example, if I suddenly decided to say t.get_two, the fact that I used the . syntax would increment @access_times by 1. Or perhaps I made a check t.is_a?(Test), it would also increment @access_times by 1. Accessing any methods or attributes inherited by Test would also increment the variable by 1.
Basically I want to add some stuff to the . syntax if possible.
I am not asking whether this is good or bad code, just whether it’s possible and how it would be done. I wouldn’t normally use it since I could just add the increment logic to every method manually and replace all direct instance variable accessing with methods (even things like is_a? and other things inherited from Object)
a pretty hardcore-version would be to use
set_trace_func: http://apidock.com/ruby/Kernel/set_trace_functhis allows you to subscribe to all the ruby events fired throughout your program, which can be a ton of calls…
i don’t think that there is a build-in hook for registering to arbitrary method-calls. you could implement something with method-missing, method-chaining or delegation, but that would depend on your requirments.