1

I would like to check when running a method, if it was called from a different method.

EX:

def method1(foo)
  if # foo previous method == method2
    #code
  elsif # foo previous method == method 3
    #code
  end
end

def method2
  method1(foo)
end

is there a way to do this?

oconn
  • 2,112
  • 2
  • 18
  • 15

1 Answers1

4

Yes, you can use caller from Kernel as described in http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-caller, although you'll need to extract the method name from the string that caller[0] returns.

Update: The little regex to extract the method name is shown in https://stackoverflow.com/a/5100339/1008891.

Community
  • 1
  • 1
Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106
  • A small clarification for readers who do not wish to check the docs: `caller` returns an array of strings that identifies the current execution stack. The first element of the array gives you calling method. – Cary Swoveland Nov 17 '13 at 03:24
  • @CarySwoveland Good clarification - my answer was pretty cryptic. I updated it slightly. – Peter Alfvin Nov 17 '13 at 03:28