Block Depth in Ruby (Exception-handling, Thread-safety & Meta-programming)
alfajango.com
alfajango.com
However, while that method would work for a simple Ruby script, it's basically useless in the context of a Rails app, or any other framework, as it will give you the total block depth within the framework. For instance, if you put that line inside a controller method in a Rails 3 app, you'll get a block depth of 10, without explicitly calling any block methods. This is usually not desirable, because we're not concerned with how many levels deep in the framework we are; we only want the block depth of our own code.
Now, obviously we could simply say:
caller.grep(/block in/).length - 10
...inside the controller method, but then it's vulnerable to changes in the framework, due to updates or whatever.Also, this would not give us the flexibility to exclude certain methods from our depth tracking.
EDIT: Oh, and most importantly, because it then wouldn't be an exercise in exception-handling, thread-safety, and meta-programming, which was the real point of writing an article about it.
Another less hacky but usually slower solution would be the over-powered but under-used set_trace_func, which would give you all the flexibility you need, although I don't know if the trace function is thread-safe (on a phone, rubydoc is a bit hard to search from here).
But, certainly, point taken about it losing its power to illustrate those techniques.