Ruby’s caller_locations method returns an array of Thread::Backtrace::Location objects for the current call stack. Unlike caller, which returns formatted strings, each location exposes queryable details such as its label, base_label, path, and line number. section 15.4.1 section 15.4.2
Tracing nested calls
With method_3 calling method_2, method_2 calling method_1, and method_1 calling caller_locations, the returned stack begins at method_2. The method that invokes caller_locations—method_1—is omitted. Reading each location lets you report messages such as “Method method_3 called from line 13 of caller_locations_demo.rb.” section 15.4.2
Useful location queries include:
- label identifies the full method label, such as Object#method_3. section 15.4.2
- base_label provides the simpler method name, such as method_3. section 15.4.2
- path and lineno identify the source file and call-site line. section 15.4.2
def method_1
puts "In method 1"
caller_locations
end
def method_2
puts "In method 2"
method_1
end
def method_3
puts "In method 3"
method_2
end
Browse the small method chain that returns caller_locations through nested calls. section 15.4.2
caller_locations supports practical diagnostics. A small testing framework can search returned locations for the first method whose label does not contain assert, reporting the failing test instead of the assertion helper. section 15.5.2
