The Method you’re in

Sometimes I like to find out in which method my programs are currently in — may be for debugging but a lot more likely to log that fact for later analysis. For some (long running) automation stuff that’s really useful. Especially if (or when) the exact order of method calls it not deterministic. Think for example of a rules based engine which randomly applies a set of rules to a set of objects.

That said, you could just make each method log it:

def method_1 "Executing #{ method_1 }" 
  # more code 

But that’s not DRY after the second method doing that. And it’s manual, cumbersome and error-prone.

Well, there’s Kernel#caller, but I was looking for something a bit more compact. So here it comes:

module MethodCallList 
  def method_name 
    list = caller[ 0..-2 ] 
    if list.empty? 
    else do | el | 
        if md = el.match( /in '(.+)'/ ) 
          md[ 1 ] 
      end.reverse.join( '/' ) 

Is there any better, more elegant or completely different way to do this in Ruby? I’d love to hear about that.
Hmm, the module name could be better than this…


One thought on “The Method you’re in

  1. Module MethodTools
    def this_method()
    caller.first[/`(.*?)’/, 1]

    If i think i know what you are asking about…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s