liveBook · Manning

Caller_locations

As explained in The Well-Grounded Rubyist, Fourth Edition

caller_locations is a Ruby Kernel method that returns structured locations for the current call stack instead of formatted location strings.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains returned location objects, stack order, omitted callers, and core queries, but stops short of implementation internals.
Examples
Uses nested methods, irb stack inspection, formatted location reports, and a MicroTest assertion-failure locator.
What it assumes
Assumes familiarity with Ruby methods and call stacks while teaching the distinction between string traces and location objects.
What you can do after
Diagnose/debug with it by locating methods, files, and lines involved in a call-stack event.
How it connects
Connects stack traces with caller, callbacks, runtime introspection, method querying, and testing frameworks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.