Ph values

Stephan on Ruby, testing, software (good and bad) and the world at large

Archive for the 'method call' Category


The Method you’re in

Posted by stephan on 28. January 2007

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
  logger.info "Executing #{ method_1 }"
  # more code
end

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?
      "method_name"
    else
      list.map do | el |
        if md = el.match( /in '(.+)'/ )
          md[ 1 ]
        else
          ''
        end
      end.reverse.join( '/' )
    end
  end
end

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…

Posted in Ruby, method call, syntax | 1 Comment »