Reputation: 19765
Let us have a following simple example:
def funny_function(param)
lineNumber = __LINE__ # this gives me the current line number
puts lineNumber
end
As we can see, I can get the current line number. However, my question is, is there a non-intrusive way to find out from which line number (and even a file) the method was called?
Non-intrusive meaning that I don't want the method user to know about that, she just has to provide the param
parameter, e.g.:
funny_function 'Haha'
Maybe something like caller.__LINE__
?
Upvotes: 3
Views: 2119
Reputation: 8656
You can use caller_locations
which has been added recently. It returns an array of Location
objects. See http://ruby-doc.org/core-2.2.3/Thread/Backtrace/Location.html for details.
No need to parse the return of caller
. Hooray.
To add on to this caller_locations.first
or caller_locations(0)
gets the last method location, increment the parameter to pull specific steps.
Upvotes: 8
Reputation: 1065
def b
puts "world"
end
def a
puts "hello"
end
p method(:a).source_location
=> ["filename.rb", 5]
Is this what your after?
Upvotes: 2
Reputation: 1854
To get the line of the ast function call caller[0].scan(/\d+/).first
:
def func0
func1
end
def func1
func2
end
def func2
func3
end
def func3
p caller[0].scan(/\d+/).first
end
func0
Upvotes: 1