On 8/29/08, Matthew Moss <matthew.moss / gmail.com> wrote:
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>
>  The three rules of Ruby Quiz 2:
>
>  1.  Please do not post any solutions or spoiler discussion for this
>  quiz until 48 hours have passed from the time on this message.
>
>  What I would like is a script that works like `which` but for Ruby
>  modules. Examples:
>
>     > ruby modwhich.rb "sys/uptime"
>     require 'sys/uptime' =>
>  /opt/local/lib/ruby/vendor_ruby/1.8/i686-darwin8.11.1/sys/uptime.bundle
>
>     > ruby modwhich.rb date
>     require 'date' => /opt/local/lib/ruby/1.8/date.rb
>

This is what came to mind. Interesting idea. I may just keep this around.

% ruby which.rb rubygems rake fake/thing date/format
"rubygems" found in /Library/Ruby/Site/1.8/rubygems.rb
"rake" found in /Library/Ruby/Site/1.8/rake.rb
Could not find "fake/thing" anywhere
"date/format" found in
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/date/format.rb

% cat which.rb
alias untracked_require require
$req = Hash.new
def require(path)
  old_features = $LOADED_FEATURES.dup
  untracked_require(path)
  $req[path] ||= ($LOADED_FEATURES - old_features).last
end

ARGV.each do |path|
  begin
    require(path)
  rescue LoadError
    $stderr.puts "Could not find #{path.inspect} anywhere"
  else
    found = $LOAD_PATH.find { |dir| File.exist? "#{dir}/#{$req[path]}" }
    $stderr.puts "#{path.inspect} found in #{found}/#{$req[path]}"
  end
end