开发者

Discover the file ruby require method would load?

开发者 https://www.devze.com 2023-01-09 22:30 出处:网络
The require method in ruby will search the lib_path and load the first matching files found if needed. Is there anyway to print the path to the file which would be loaded. I\'m looking for, ideally bu

The require method in ruby will search the lib_path and load the first matching files found if needed. Is there anyway to print the path to the file which would be loaded. I'm looking for, ideally built-in, functionality similar to the which command in bash and hoping it can be tha开发者_JAVA技巧t simple too. Thanks.


I don't know of a built-in functionality, but defining your own isn't hard. Here's a solution adapted from this question:

def which(string)
  $:.each do |p|
    if File.exist? File.join(p, string)
      puts File.join(p, string)
      break
    end
  end
end

which 'nokogiri'
#=> /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri

Explanation: $: is a pre-defined variable. It's an array of places to search for files you can load or require. The which method iterates through each path looking for the file you called it on. If it finds a match, it returns the file path.

I'm assuming you just want the output to be a single line showing the full filepath of the required file, like which. If you want to also see the files your required file will load itself, something like the solution in the linked question might be more appropriate:

module Kernel
  def require_and_print(string)
    $:.each do |p|
      if File.exist? File.join(p, string)
        puts File.join(p, string)
        break
      end
    end
    require_original(string)
  end

  alias_method :require_original, :require
  alias_method :require, :require_and_print

end

require 'nokogiri'
#=>  /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/rubygems-update-1.3.5/lib/rbconfig
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/pp
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/sax
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/xpath
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xslt
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/html
#    /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/css
#    /opt/local/lib/ruby1.9/1.9.1/racc/parser.rb  


$ gem which filename # (no .rb suffix) is what I use...

0

精彩评论

暂无评论...
验证码 换一张
取 消