コードで場所を追跡する方法を示す簡単な例を次に示します。モジュール内の場所を知る必要がある場合:
class Foo
attr_reader :initialize_loc
def initialize
@initialize_loc = [__FILE__, __LINE__]
# do more stuff...
end
end
何かが起こった場所を知る必要がある場合:
require_relative 't1'
foo = Foo.new
# do lots of stuff until you want to know where something was initialized.
puts 'foo initialized at %s:%s' % foo.initialize_loc
コードを実行すると、次のようになります。
FooBar:Desktop foobar ruby t2.rb
foo initilized at /Users/foobar/Desktop/t1.rb:4
モジュールのソースコードをいじりたくなく、必要なときにデバッガーにジャンプさせたい場合は、デバッガーにそれを実行させます。
require_relative 't1'
require 'ruby-debug'
debugger
foo = Foo.new
# do lots of stuff until you want to know where something was initilized.
puts 'foo initilized at %s:%s' % foo.initialize_loc
実行が停止し、デバッガーの次の行にドロップしますdebugger
。
[0, 9] in t2.rb
1 require_relative 't1'
2 require 'ruby-debug'
3
4 debugger
=> 5 foo = Foo.new
6 # do lots of stuff until you want to know where something was initilized.
7 puts 'foo initilized at %s:%s' % foo.initialize_loc
8
t2.rb:5
foo = Foo.new
(rdb:1)
次のコード行に簡単s
に「ステップ」します。これは、のinitialize
ブロックになりFoo
ます。
(rdb:1) s
[-1, 8] in /Users/foobar/Desktop/t1.rb
1 class Foo
2 attr_reader :initialize_loc
3 def initialize
=> 4 @initialize_loc = [__FILE__, __LINE__]
5 # do more stuff...
6 end
7 end
8
/Users/foobar/Desktop/t1.rb:4
@initialize_loc = [__FILE__, __LINE__]
(rdb:1)
これを超えて、ディレクトリを再帰的に検索し、ファイル名とターゲットに一致する行の行番号をリストするなどのツールを使用grep -rn target_to_find path_to_search
すると、探しているものを見つけるのに大いに役立ちます。
または、:vim /target_to_find/ path_to_search
Vim 内から を使用すると、探しているファイルが返されます。