機略戦記

Maneuver warfare

rails console上で、あるメソッドが定義されているファイルをshellを使わず直接エディタで開きたい

結論

# Rails.cache.read の定義ファイルを開きたい
# 以下を実行すると、おもむろにatomが立ち上がる
pry(main)> `atom #{Rails.cache.method(:read).source_location.first}`

解説

あるメソッドがどのファイルに定義されているか得る

  • #methodMethodオブジェクトを取り出す。
  • Methodオブジェクトに対して、#source_locationで定義ファイル位置を取り出す。
pry(main)> Rails.cache.method(:read).source_location
=> ["/Users/nagai_shinya/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/dalli-2.7.0/lib/active_support/cache/dalli_store.rb", 113]
pry(main)> Rails.cache.method(:read).source_location.first
=> "/Users/nagai_shinya/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/dalli-2.7.0/lib/active_support/cache/dalli_store.rb"

特定のファイルをrails consoleからエディタで開く

  • rails console上で``でくくった文字列を評価すると、シェルで実行される。
  • ``内で、#{}による展開ができる。

組み合わせる

  • 冒頭に書いたやつになる。