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 this? thanks in advance.
EDIT Clarification from the comments:
I want to know where the loaded "somefile" is located while I execute this line: "load somefile"
Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.
The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.
Pathname represents the name of a file or directory on the filesystem, but not the file itself. The pathname depends on the Operating System: Unix, Windows, etc.
How about simple (from a quicky test in Camping):
File.expand_path(File.dirname(__FILE__))
?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With