Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload rubygem in IRB

Is there a way to "reload" or "refresh" a rubygem in memory? As i'm playing in irb, occasionally I like to modify my gem files, and if i require the same gem, it does not update into memory and gives the output "false". Currently I have to exit IRB, get back into IRB and then require the gem again, there has to be a better way...what is it?

like image 622
Schneems Avatar asked Aug 11 '10 21:08

Schneems


3 Answers

As others have suggested, you can use Kernel#load. However, don't waste your time finding and loading each gem file as all files that have been required are stored in $". Armed with this knowledge, here's a reload irb command:

 def reload(require_regex)
  $".grep(/^#{require_regex}/).each {|e| load(e) }
 end

For example, if you were using the hirb gem in irb, you would simply reload with:

>> reload 'hirb'

If for whatever reason load doesn't work (it is pickier about file extensions than require is), you can re-require any file by first deleting its entry in $". With this advice the above command would be:

 def reload(require_regex)
   $".grep(/^#{require_regex}/).each {|e| $".delete(e) && require(e) }
 end

Pick whichever works for you. Personally, I use the latter.

like image 161
cldwalker Avatar answered Nov 19 '22 07:11

cldwalker


load 'filename.rb'

one at a time for each that was changed...

like image 33
rogerdpack Avatar answered Nov 19 '22 07:11

rogerdpack


One way is to use Kernel#load. You can use it pretty much like Kernel#require, except that you have to explicitly include the file extension. However, it has its drawbacks (even something as simple as class Foo < Struct.new(:foo); end fails, as it is not possible to change the superclass of an class), so I would also like to know a better way to do this.

In rails you can achieve this with reload! on script/console, but I don't know what kind of magic they use.

This gist looks promising but I haven't tested it.

like image 6
sluukkonen Avatar answered Nov 19 '22 08:11

sluukkonen