標籤:style ar 檔案 on ad ef size as 程式
classtrace.rb:
#encoding: utf-8module ClassTrace T = [] #定義常數陣列T,存放trace資訊 if x = ARGV.index("--traceout") #如果ruby命令後面有--traceout參數,則記錄到檔案中,否則輸出 OUT = File.open(ARGV[x + 1], ‘w‘) ARGV[x, 2] = nil else OUT = STDERR endendalias origin_require require #給require定義別名方法origin_require,下面要重新定義alias origin_load load #給load方法定義別名方法origin_load,下面要重新定義load方法def require(file) ClassTrace::T << [file, caller[0]] #將require方式載入的檔案和載入該檔案的位置放入一個數組,並添加到T常量中 origin_require(file) #require負載檔案enddef load(*args) ClassTrace::T << [args[0], caller[0]] #將load方式載入的檔案和載入該檔案的位置放入一個數組 origin_load(*args) #load負載檔案enddef Object.inherited(c) #定義鉤子方法inherited方法,當有新的類定義時調用此方法將類名和定義的位置加入到T常量 ClassTrace::T << [c, caller[0]] endat_exit{ #當程式退出執行時 o = ClassTrace::OUT o.puts ‘=‘ * 60 o.puts ‘Files Loaded and Classes Defined:‘ o.puts ‘=‘ * 60 ClassTrace::T.each do |what, where| #遍曆trace資訊數組T,將資訊寫入到檔案或輸出 if what.is_a? Class o.puts "Defined: #{what.ancestors.join(‘<-‘)} at #{where}" else o.puts "Loaded: #{what} at #{where}" end end}
index.rb
#encoding: utf-8require ‘./classtrace‘require ‘./test‘class Test; endputs "11111"
test.rb
#encoding: utf-8class TestClass; end
ruby index.rb --traceout /tmp/trace #將index.rb檔案中載入的檔案和定義的類的trace資訊寫入到/tmp/trace檔案,像這樣:
============================================================
Files Loaded and Classes Defined:
============================================================
Loaded: ./test at index.rb:3:in `<main>‘
Defined: TestClass<-Object<-Kernel<-BasicObject at /Users/fangxiang/work/ruby/test/test.rb:2:in `<top (required)>‘
Defined: Test<-Object<-Kernel<-BasicObject at index.rb:4:in `<main>‘
ruby追蹤檔案載入和類的定義