How do I get a list of files that have been `required` in Ruby?

前端 未结 3 1175
遥遥无期
遥遥无期 2020-12-28 13:37

This is purely an experiment, but I\'m wondering if it\'s possible to get a list of the require\'d gems at runtime via some kind of metaprogramming. For example

3条回答
  •  [愿得一人]
    2020-12-28 14:14

    Here's a way to get all the calls to require. Create this file: show_requires.rb

    alias :orig_require :require
    def require s
      print "Requires #{s}\n" if orig_require(s)
    end
    

    Then start your app with

    ruby -r show_requires.rb myapp.rb

    This produces something like:

    C:\code\test>ruby -r show_requires.rb test.rb
    Requires stringio
    Requires yaml/error
    Requires syck
    Requires yaml/ypath
    Requires yaml/basenode
    Requires yaml/syck
    Requires yaml/tag
    Requires yaml/stream
    Requires yaml/constants
    Requires date/format
    Requires date
    Requires yaml/rubytypes
    Requires yaml/types
    Requires yaml
    Requires etc
    Requires dl
    Requires rbreadline
    Requires readline
    

    If you want only the top-level requires, add a global to track the nesting level:

    $_rq_lvl = 0
    alias :orig_require :require
    def require s
      $_rq_lvl+=1
      print "Requires #{s}\n" if orig_require(s) and $_rq_lvl == 1
      $_rq_lvl -=1
    end
    

    Then you get:

    C:\code\test>ruby -r require_test.rb test.rb
    Requires yaml
    Requires readline
    

提交回复
热议问题