How does require rubygems help find rubygem files?

后端 未结 1 1550
生来不讨喜
生来不讨喜 2020-12-11 03:53

While trying to solve Gem found in irb, not in Ruby , I tried seeing what effect require \'rubygems\' had on my own installation:

$ irb
irb(main         


        
1条回答
  •  抹茶落季
    2020-12-11 04:12

    Here's the current version of the relevant source: https://github.com/rubygems/rubygems/blob/02ead548e38ff90923444fa7c0ff9f6a5dbd87b0/lib/rubygems/custom_require.rb. (Edit: here's an earlier version (1.5.2) that more clearly expresses what happens.)

    The docs say:

    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:

    • If the file can be loaded from the existing Ruby loadpath, it is.
    • Otherwise, installed gems are searched for a file that matches. If it's found in gem 'y', that gem is activated (added to the loadpath).

    The normal require functionality of returning false if that file has already been loaded is preserved.

    It does this by opening up module Kernel and aliasing the original require with alias gem_original_require require, then redefining require to first call the original version, and look at the gems if that doesn't work.

    So the load path is only changed when you require a gem:

    ruby-1.8.7-p330 :002 > $:.length
    => 9 
    ruby-1.8.7-p330 :003 > require 'rubygems'
    => true 
    ruby-1.8.7-p330 :004 > $:.length
    => 9 
    ruby-1.8.7-p330 :005 > require 'haml'
    => true 
    ruby-1.8.7-p330 :006 > $:.length
    => 10 
    

    0 讨论(0)
提交回复
热议问题