Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discover the file ruby require method would load?

Tags:

ruby

rubygems

irb

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 that simple too. Thanks.

like image 421
Blake Taylor Avatar asked Dec 31 '25 22:12

Blake Taylor


2 Answers

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  
like image 83
michaelmichael Avatar answered Jan 03 '26 13:01

michaelmichael


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

like image 30
rogerdpack Avatar answered Jan 03 '26 12:01

rogerdpack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!