Module | Kernel |
In: |
lib/rubygems/custom_require.rb
lib/rubygems.rb |
require | -> | gem_original_require |
The Kernel#require from before RubyGems was loaded. |
Use Kernel#gem to activate a specific version of gem_name.
version_requirements is a list of version requirements that the specified gem must match, most commonly "= example.version.number". See Gem::Requirement for how to specify a version requirement.
If you will be activating the latest version of a gem, there is no need to call Kernel#gem, Kernel#require will do the right thing for you.
Kernel#gem returns true if the gem was activated, otherwise false. If the gem could not be found, didn‘t match the version requirements, or a different version was already activated, an exception will be raised.
Kernel#gem should be called before any require statements (otherwise RubyGems may load a conflicting library version).
In older RubyGems versions, the environment variable GEM_SKIP could be used to skip activation of specified gems, for example to test out changes that haven‘t been installed yet. Now RubyGems defers to -I and the RUBYLIB environment variable to skip activation of a gem.
Example:
GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb
# File lib/rubygems.rb, line 65 65: def gem(gem_name, *version_requirements) # :doc: 66: skip_list = (ENV['GEM_SKIP'] || "").split(/:/) 67: raise Gem::LoadError, "skipping #{gem_name}" if skip_list.include? gem_name 68: Gem.activate(gem_name, *version_requirements) 69: end
When RubyGems is required, Kernel#require is replaced with our own which is capable of loading gems on demand.
When you call require ‘x‘, this is what happens:
The normal require functionality of returning false if that file has already been loaded is preserved.
# File lib/rubygems/custom_require.rb, line 30 30: def require(path) # :doc: 31: gem_original_require path 32: rescue LoadError => load_error 33: if load_error.message =~ /#{Regexp.escape path}\z/ and 34: spec = Gem.searcher.find(path) then 35: Gem.activate(spec.name, "= #{spec.version}") 36: gem_original_require path 37: else 38: raise load_error 39: end 40: end