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__
?
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.
def b
puts "world"
end
def a
puts "hello"
end
p method(:a).source_location
=> ["filename.rb", 5]
Is this what your after?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With