読者です 読者をやめる 読者になる 読者になる

せかいや

いまいるここを、おもしろく http://sekai-in-the-box.appspot.com/

【Ruby】【メタプログラミング】require,load,クラス定義,プログラム終了のトレーシング

 
■topic summary
study about tracing require, load, define-class, exit-program

 

ポイント

・at_exitはブロックを登録(再定義しない)
・loadメソッドはファイル名を指定(※1)


※1

(ここでは簡単な例としてライブラリをロードしてみたが、)フルパスを指定して リソースファイルをロードしたりするのがloadのまっとうな使いかたである。

http://www.loveruby.net/ja/rhg/book/load.html

 

module ClassTrace
  alias original_require require
  alias original_load load
  T = []
  def require(file)
    T << ["require: ", file, caller[0]]
    original_require(file)
  end
  def load(file)
    T << ["load: ", file, caller[0]]
    original_load(file)
  end
  def Object.inherited(c)
    T << ["inherited: ", c, caller[0]]
  end
  at_exit{T.each {|t| p t}}
end
include ClassTrace
require "bigdecimal"
load "test.rb"
class Test
end

 
 
■実行結果

["require: ", "bigdecimal", "C:/Users/HOGE_ADMIN/Desktop/test/arrays.rb:22:in `<main>'"]
["require: ", "rubygems/requirement", "C:/Ruby200/lib/ruby/2.0.0/rubygems/dependency.rb:4:in `<top (required)>'"]
["inherited: ", Gem::Dependency, "C:/Ruby200/lib/ruby/2.0.0/rubygems/dependency.rb:6:in `<top (required)>'"]
["inherited: ", Gem::PathSupport, "C:/Ruby200/lib/ruby/2.0.0/rubygems/path_support.rb:6:in `<top (required)>'"]
["inherited: ", BigDecimal, "C:/Ruby200/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require'"]
["load: ", "test.rb", "C:/Users/HOGE_ADMIN/Desktop/test/arrays.rb:23:in `<main>'"]
["require: ", "benchmark", "test.rb:1:in `<top (required)>'"]
["inherited: ", Benchmark::Job, "C:/Ruby200/lib/ruby/2.0.0/benchmark.rb:306:in `<module:Benchmark>'"]
["inherited: ", Benchmark::Report, "C:/Ruby200/lib/ruby/2.0.0/benchmark.rb:344:in `<module:Benchmark>'"]
["inherited: ", Benchmark::Tms, "C:/Ruby200/lib/ruby/2.0.0/benchmark.rb:380:in `<module:Benchmark>'"]
["inherited: ", Test, "C:/Users/HOGE_ADMIN/Desktop/test/arrays.rb:24:in `<main>'"]


ふむふむ。