Reload rubygems in irb?
Asked Answered
S

3

9

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?

Santiago answered 27/4, 2011 at 15:57 Comment(2)
This question was answered before https://mcmap.net/q/275967/-reload-rubygem-in-irb/…Denicedenie
I've already tried using that solution and it did not work.Santiago
H
10

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.

Hennery answered 27/4, 2011 at 16:18 Comment(1)
Thanks. Here is the final version of the script above.Santiago
D
3

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

Deferential answered 27/4, 2011 at 16:4 Comment(2)
I've used exec "irb -r #{this}" before. The problem is that it will "unload" all of my gems. So if I for example did this. require "random"; r "something" then random won't be loaded after installing something.Santiago
This answer might have what you're looking for then.Deferential
U
0

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

Unworldly answered 27/4, 2011 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.