Reload rubygems in irb?

2019-04-06 01:41发布

问题:

I've this script right now.

def r(this)
  require this
  puts "#{this} is now loaded."
rescue LoadError
  puts "The gem '#{this}' is missing."
  puts "Should I install it? [y/n]"
  data = gets
  if data =~ /yes|y/i
    puts "Installing #{this}, hold on."
    if `gem install #{this}` =~ /Successfully/i
      load this
    end
  else
    puts "Okey, goodbye."
  end
end

That makes it possible to require libs on the fly. Like this: r "haml".

The problem is that I can't load the gem after it has been installed. Using load this or load File.expand_path("~/.irbrc") does not work.

Here is an example.

>> r "absolutize"
The gem 'absolutize' is missing.
Should I install it? [y/n]
y
Installing absolutize, hold on
LoadError: no such file to load -- absolutize
>> require "absolutize"
LoadError: no such file to load -- absolutize
>> exit
$ irb
>> require "absolutize"
=> true

Is there a way to reload rubygems or irb on the fly?

回答1:

I did not try, but I think you might be looking for Gem.clear_paths

Reset the dir and path values. The next time dir or path is requested, the values will be calculated from scratch. This is mainly used by the unit tests to provide test isolation.



回答2:

You can reset irb by calling exec('irb')



回答3:

Just remove the file from ´$"´:

require 'erb' # Loaded.
require 'erb' # Does nothing.
$".delete_if {|e| e =~ /erb\.(?:rb|so)/} # Remove "erb" from loaded libraies.
require 'erb' # Reloaded (with warnings if the first require was successful).

See http://www.zenspider.com/Languages/Ruby/QuickRef.html#19