How to require for the second time How to require for the second time ruby ruby

How to require for the second time


load does not require (hmm) a full path. It expects a complete filename with an extension.

p load 'date.rb' #=> truep load 'date.rb' #=> truep load 'date'    #=> LoadError


:000> path = "extremely/long/path/to/my/file":001> load path:002> load path


You could write your own and put it in your .irbrc:

New Hotness

module Kernel  def reload(lib)    if old = $LOADED_FEATURES.find{|path| path=~/#{Regexp.escape lib}(\.rb)?\z/ }      load old    else      require lib    end  endend

Minutes-Old and Therefore Busted

module Kernel  # Untested  def reload(lib)    if File.exist?(lib)      load lib    else      lib = "#{lib}.rb" unless File.extname(lib)=='.rb'      $:.each do |dir|        path = File.join(dir,lib)        return load(path) if File.exist?(path)      end    end  endend

For the old-and-busted version you would have to make it more robust if you wanted to support RubyGems.

One problem with either of these solutions is that while it will force-reload the file in question, if that file in turn calls require on others (as is usually the case with gems) those files will not be reloaded.

Working around this would be really ugly. Like, maybe manually reaching into the $LOADED_FEATURES array and ripping out all the paths that looked to be related to the gem's name. shudder