Joseph Weissman Joseph Weissman - 1 year ago 70
Ruby Question

Any way to determine which object called a method?

I'm hoping that Ruby's message-passing infrastructure means there might be some clever trick for this.

How do I determine the calling object -- which object called the method I'm currently in?

Answer Source

As an option, there is a binding_of_caller gem that allows you to execute code in context of any caller on the call stack (caller, caller's caller and so on). It's useful for inspecting (read do anything at any position on the call stack) call stack in development, as used in better_errors.

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use.

Should I mention, this technique should only be used for debugging, fun or educational purposes, because it violates principles of OOP really badly.
Mostly because of eval.

Let's prepare stuff:

require 'binding_of_caller' # I assume, you installed this gem already?

Get the immediate (closest on stack, hence 0) caller instance:


...or even an immediate calling method:


If you need to get higher up the call stack, use numbers other than 0 for getting a caller's binding.

Awfully hacky. But if you really need this — there you go.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download