Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to determine which object called a method?

Tags:

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?

like image 869
Joseph Weissman Avatar asked Apr 24 '10 03:04

Joseph Weissman


People also ask

Can an object call a method?

Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.

Can I use this inside an object js?

“this” is not bound In JavaScript, keyword this behaves unlike most other programming languages. It can be used in any function, even if it's not a method of an object. The value of this is evaluated during the run-time, depending on the context. The rule is simple: if obj.


2 Answers

You can easily look at the line of code that called the function of interest through

caller.first 

which will tell you the filename and line number which called the relevant function. You could then back-calculate which object it was.

However, it sounds like you're more after some object that called a certain function, perhaps within an instance method. I'm not aware of a method for figuring this out - but I wouldn't use it anyway, since it seems to violate encapsulation badly.

like image 179
Peter Avatar answered Sep 20 '22 06:09

Peter


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.

– http://www.ruby-doc.org/core-2.1.4/Binding.html

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:

binding.of_caller(0).eval('self') 

...or even an immediate calling method:

binding.of_caller(0).eval('__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.

like image 30
D-side Avatar answered Sep 18 '22 06:09

D-side