Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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"

like image 561
eric2323223 Avatar asked Jan 19 '09 02:01

eric2323223


People also ask

How do I get the full path of a file in Ruby?

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.

What does __ file __ mean in Ruby?

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.

What is path in Ruby?

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.


3 Answers

Show a file's pathname in Ruby

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

File.expand_path(File.dirname(__FILE__))

?

like image 168
Dave Everitt Avatar answered Oct 20 '22 20:10

Dave Everitt


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.

like image 28
Gordon Wilson Avatar answered Oct 20 '22 21:10

Gordon Wilson


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

like image 44
Tilo Avatar answered Oct 20 '22 20:10

Tilo