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

前端 未结 3 1187
遥遥无期
遥遥无期 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:25

    Just a slight touch to add to the previous -- consider that in order to precisely replace the behaviour of #require then you must also return a boolean value, so this is a more faithful override:

    module Kernel
      alias :orig_require :require
      def require(name)
        print "Requiring #{name}"
        is_okay = orig_require(name)
        puts " - #{is_okay ? 'Yup!' : 'Nope :('}"
        is_okay
      end
    end
    

    Interestingly with some testing I was doing -- tracking down a chain of stuff blowing up when requiring a module -- then this became necessary!

提交回复
热议问题