やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

組込ライブラリ(Thread::Backtrace::Location)

 Rubyのフレーム。

成果物

情報源

Thread::Backtrace::Location

Ruby のフレームを表すクラスです。

Kernel.#caller_locations から生成されます。

例1:

# caller_locations.rb
def a(skip)
  caller_locations(skip)
end
def b(skip)
  a(skip)
end
def c(skip)
  b(skip)
end

c(0..2).map do |call|
  puts call.to_s
end

例1の実行結果:

caller_locations.rb:2:in `a'
caller_locations.rb:5:in `b'
caller_locations.rb:8:in `c'

 メソッド名などが取得できる。他にもファイルパスや行数も。

例2:

# foo.rb
class Foo
  attr_accessor :locations
  def initialize(skip)
    @locations = caller_locations(skip)
  end
end

Foo.new(0..2).locations.map do |call|
  puts call.to_s
end

例2の実行結果:

init.rb:4:in `initialize'
init.rb:8:in `new'
init.rb:8:in `<main>'

参考 Ruby VM アドベントカレンダー #4 vm_backtrace.c: https://www.atdot.net/~ko1/diary/201212.html#d4

メンバ抜粋

インスタンスメソッド

absolute_path base_label inspect label lineno path to_s

対象環境

$ uname -a
Linux raspberrypi 5.10.52-v7l+ #1441 SMP Tue Aug 3 18:11:56 BST 2021 armv7l GNU/Linux