Show full path name of the ruby file when it get loaded

前端 未结 5 585
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 05:04

When reading source code, I always want to know the full path of the file when it is loaded, is there any callback method in ruby to accomplish this, or any other way to do

相关标签:
5条回答
  • 2020-12-10 05:23

    Show a file's pathname in Ruby

    How about simple (from a quicky test in Camping):

    File.expand_path(File.dirname(__FILE__))
    

    ?

    0 讨论(0)
  • 2020-12-10 05:24

    To get the full path of the file, you must assemble a string in the following way (where yourfileobject is an object of Ruby's File class).

    File.expand_path(File.dirname(yourfileobject)) + "/" + yourfileobject.path
    
    0 讨论(0)
  • 2020-12-10 05:28

    The best way I can think of is to patch the Kernel module. According to the docs Kernel::load searches $: for the filename. We can do the same thing and print the path if we find it.

    module Kernel
      def load_and_print(string)
        $:.each do |p|
          if File.exists? File.join(p, string)
            puts File.join(p, string)
            break
          end
        end
        load_original(string)
      end
    
      alias_method :load_original, :load
      alias_method :load, :load_and_print
    
    end
    

    We use alias_method to store the original load method, which we call at the end of ours.

    0 讨论(0)
  • 2020-12-10 05:29

    Gordon Wilson's answer is great, just wanted to add that you can also see which libraries were loaded (and their complete path!) , by looking at the output of the variable $" (returns an array of absolute file names)

    e.g. the path of the most recently loaded library is at the end of the array

    0 讨论(0)
  • 2020-12-10 05:39

    I'm curious why you're using load instead of require - in all of my time using Ruby. I've never had occasion to utilize load.

    0 讨论(0)
提交回复
热议问题