Search code examples
rubymodel-view-controllerrenderrhtml

Count how many methods are in a method?


So if there are two methods:

def foo
   method1
   method2
end

How could one check to see if all of these 'method1/method2' have been executed in the method themselves? How could the amount of times that the method is being called being counted. The code also needs to be inside the method1 or method2 to check this.


Solution

  • It's probably easy to do it another way, but this way seems clean and modular.

    Create a proxy class called method_counter which removes it's own methods, and defines missing_method, get_method_counts, and a constructor. You can see examples of how to do that here: http://www.binarylogic.com/2009/08/07/how-to-create-a-proxy-class-in-ruby/

    Now the constructor takes any other object, and stores it internally. The get method counts method returns a hash of methodname => count objects.

    The missing method gets called by ruby whenever someone calls a method on the proxy object that doesnt exist... And then you should implement it to call the same method on the contained object (passed in the constructor) after updating the method count hash.

    This implementation is clean because you have not touched the target objects code, and the calling code will only have to change 1 line (the constructor of the target object to create a proxy instead).