
Block Depth in Ruby (Exception-handling, Thread-safety & Meta-programming) - JangoSteve
http://www.alfajango.com/blog/counting-block-nesting-depth-in-ruby/
======
1337p337
Is there some reason the author doesn't use caller.grep(/block in/).length ?
Because that is right there in the language and doesn't require any of that
instance variable tracking or "_with_" method syntax.

~~~
JangoSteve
The main reason is that no one really thought of that, kudos (and upvoted) ;-)

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.

~~~
1337p337
Instead of subtracting 10, since the caller method provides filenames, just
before the .grep you could call .reject to filter out all the framework code,
or perhaps .take_while to stop when you've hit a certain point. (Those would
also work for filtering our places you want to turn off tracing.)

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.

