Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to know the invoking method?

Tags:

ruby

callstack

I know the class method tells what is the name of the class of an object, how could I know the name of the invoking method? Is there a way to know that?

like image 332
Werner Echezuria Avatar asked Dec 07 '09 13:12

Werner Echezuria


People also ask

How do you find the calling method?

To get name of calling method use method StackTrace. GetFrame. Create new instance of StackTrace and call method GetFrame(1). The parameter is index of method call in call stack.

How do you find out who called a method in Java?

Sometimes it is nice to access the caller of a method. Doing this is relatively simple, you can use the getStackTrace() method on the current thread. This returns the call stack in reverse order, e.g. the first element is the own call, the second element the direct caller and so on.

What happens when a method is invoked?

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires.


2 Answers

Examining the Ruby Call Stack shares this information:

Have you ever wanted to look at the call stack without raising an exception to do it?

caller.each {|c| puts c}
like image 93
DOK Avatar answered Sep 18 '22 02:09

DOK


caller is a kernal method that lets you do this, so caller[0] will let you know the immediate caller of the function.

a quick hack to get only the name of the function could be

caller[0][/`\S+/].chop[1..-1]

this will return the name of the calling method as a String, which you can then use however you want

like image 38
user214028 Avatar answered Sep 21 '22 02:09

user214028