閱讀689 返回首頁    go 阿裏雲 go 技術社區[雲棲]


rails應用遍曆Controllers目錄並取出所有的Controller和action

今天在javaeye論壇上看到有人有這個需求,順手寫了下。原理就是通過遍曆Controllers目錄,並用正則表達式取出Controller名和它所有的action。

    @controllers=Hash.new
    path
="#{RAILS_ROOT}/app/controllers/"
    Dir
.new(path).entries.each do |f|
      
if !f.index('.rb').nil? and f.index('.rb')>0
        
        controller
=File.open(path+f.to_s)
        s
=controller.read
         
/class\s(.*)\s\</.match(s)
        controller_name
=$1.to_s
        actions
=[]
        s
.scan(/def\s(.*)\s/).each|action| actions<<(action[0]) }
        
@controllers[controller_name]=actions
        controller
.close
      end
    end
    
    
@controllers.each_pair do |name, actions|
      actions
.each do |action| 
        puts 
|name<<" "<<action
      end
    end
文章轉自莊周夢蝶  ,原文發布時間5.17

最後更新:2017-05-17 13:34:58

  上一篇:go  JUnit源碼分析 (三)——Template Method模式
  下一篇:go  JUnit源碼分析(二)——觀察者模式