Ruby 读 RubyGems 源码遇到的问题

hiveer · 2017年02月28日 · 最后由 hiveer 回复于 2017年03月01日 · 2276 次阅读

https://github.com/rubygems/rubygems/blob/v2.6.10/lib/rubygems/core_ext/kernel_require.rb#L39

# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'monitor'

module Kernel

  RUBYGEMS_ACTIVATION_MONITOR = Monitor.new # :nodoc:

  if defined?(gem_original_require) then
    # Ruby ships with a custom_require, override its require
    remove_method :require
  else
    ##
    # The Kernel#require from before RubyGems was loaded.

    alias gem_original_require require
    private :gem_original_require
  end

  ##
  # When RubyGems is required, Kernel#require is replaced with our own which
  # is capable of loading gems on demand.
  #
  # When you call <tt>require 'x'</tt>, 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 <tt>require</tt> functionality of returning false if
  # that file has already been loaded is preserved.

  def require path
    RUBYGEMS_ACTIVATION_MONITOR.enter

    path = path.to_path if path.respond_to? :to_path

    spec = Gem.find_unresolved_default_spec(path)
    if spec
      Gem.remove_unresolved_default_spec(spec)
      Kernel.send(:gem, spec.name)
    end

    # If there are no unresolved deps, then we can use just try
    # normal require handle loading a gem from the rescue below.

    if Gem::Specification.unresolved_deps.empty? then
      RUBYGEMS_ACTIVATION_MONITOR.exit
      return gem_original_require(path)
    end

    # If +path+ is for a gem that has already been loaded, don't
    # bother trying to find it in an unresolved gem, just go straight
    # to normal require.
    #--
    # TODO request access to the C implementation of this to speed up RubyGems

    spec = Gem::Specification.find_active_stub_by_path path

    begin
      RUBYGEMS_ACTIVATION_MONITOR.exit
      return gem_original_require(path)
    end if spec

    # Attempt to find +path+ in any unresolved gems...

    found_specs = Gem::Specification.find_in_unresolved path

    # If there are no directly unresolved gems, then try and find +path+
    # in any gems that are available via the currently unresolved gems.
    # For example, given:
    #
    #   a => b => c => d
    #
    # If a and b are currently active with c being unresolved and d.rb is
    # requested, then find_in_unresolved_tree will find d.rb in d because
    # it's a dependency of c.
    #
    if found_specs.empty? then
      found_specs = Gem::Specification.find_in_unresolved_tree path

      found_specs.each do |found_spec|
        found_spec.activate
      end

    # We found +path+ directly in an unresolved gem. Now we figure out, of
    # the possible found specs, which one we should activate.
    else

      # Check that all the found specs are just different
      # versions of the same gem
      names = found_specs.map(&:name).uniq

      if names.size > 1 then
        RUBYGEMS_ACTIVATION_MONITOR.exit
        raise Gem::LoadError, "#{path} found in multiple gems: #{names.join ', '}"
      end

      # Ok, now find a gem that has no conflicts, starting
      # at the highest version.
      valid = found_specs.reject { |s| s.has_conflicts? }.first

      unless valid then
        le = Gem::LoadError.new "unable to find a version of '#{names.first}' to activate"
        le.name = names.first
        RUBYGEMS_ACTIVATION_MONITOR.exit
        raise le
      end

      valid.activate
    end

    RUBYGEMS_ACTIVATION_MONITOR.exit
    return gem_original_require(path)
  rescue LoadError => load_error
    RUBYGEMS_ACTIVATION_MONITOR.enter

    begin
      if load_error.message.start_with?("Could not find") or
          (load_error.message.end_with?(path) and Gem.try_activate(path)) then
        require_again = true
      end
    ensure
      RUBYGEMS_ACTIVATION_MONITOR.exit
    end

    return gem_original_require(path) if require_again

    raise load_error
  end

  private :require

end

这里的测试设置path='active_support',active_support 已经在本地安装了。

active_model_serializers (0.10.1, 0.8.3)
activemodel (4.1.14.2)
activerecord (4.1.14.2)
activesupport (4.1.14.2)
omniauth-active_passport (0.0.3)
redis-activesupport (4.1.5)

pry 进入 console,查看$:

=> ["/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/slop-3.6.0/lib",
 "/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/method_source-0.8.2/lib",
 "/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/pry-0.10.3/lib",
 "/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/coderay-1.1.1/lib",
 "/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/pry-nav-0.2.4/lib",
 "/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/pry-rails-0.3.4/lib",
 "/Users/hiveerli/.rvm/gems/ruby-2.1.2@acl-api/gems/pry-remote-0.1.8/lib",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/site_ruby/2.1.0",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/site_ruby/2.1.0/x86_64-darwin14.0",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/site_ruby",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/vendor_ruby/2.1.0",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/vendor_ruby/2.1.0/x86_64-darwin14.0",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/vendor_ruby",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0",
 "/Users/hiveerli/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/x86_64-darwin14.0"]

并没有 active_support 的 lib,所以下面的结果可以预见

[2] pry(main)> gem_original_require 'active_support'
LoadError: cannot load such file -- active_support
from (pry):2:in `require'

然后手动测试 RubyGems 的 require 代码:

[1] pry(main)> path = 'active_support'
=> "active_support"
[2] pry(main)> RUBYGEMS_ACTIVATION_MONITOR.enter
=> 1
[3] pry(main)> path.respond_to? :to_path
=> false
[4] pry(main)> Gem.find_unresolved_default_spec(path)
=> nil
[5] pry(main)> Gem::Specification.unresolved_deps.empty?
=> true
[6] pry(main)> RUBYGEMS_ACTIVATION_MONITOR.exit
=> #<mutex:0x007fecaf079c90>
[8] pry(main)> gem_original_require(path)
LoadError: cannot load such file -- active_support

结果走不下去了? 求解

但是如果我直接调用require 'active_support'还是 work 的,迷惑不解中……

问题已经解决

正如评论中 1 楼所讲,其实源代码里面有一个 rescue,在 rescue 中有这样的一个条件表达式load_error.message.end_with?(path) and Gem.try_activate(path)

我们的错误信息是"LoadError: cannot load such file -- active_support",这满足了load_error.message.end_with?(path)

而并列的第二表达式也是返回true

[20] pry(main)> Gem.try_activate(path)
=> true

所以接下来会执行 return gem_original_require(path) if require_again,大家可以看到这里又在用原始的 require 来加载了。

但是意外的是这里会成功,原因在于在条件判断的时候 我们执行了Gem.try_activate(path)

这里会调用到Gem::Specification#activate,而这个方法又有这样的一个调用add_self_to_load_path,源码如下

def add_self_to_load_path
  return if default_gem?

  paths = full_require_paths

  # gem directories must come after -I and ENV['RUBYLIB']
  insert_index = Gem.load_path_insert_index

  if insert_index then
    # gem directories must come after -I and ENV['RUBYLIB']
    $LOAD_PATH.insert(insert_index, *paths)
  else
    # we are probably testing in core, -I and RUBYLIB don't apply
    $LOAD_PATH.unshift(*paths)
  end
end

到这里自然明白,为什么最后对gem_original_require的 call 会成功了!

底下有 rescue

mizuhashi 回复

谢谢提醒,怎么忘了这点了。看到错误信息都没想到去看看有没有 rescue,愚钝了。

hiveer 关闭了讨论。 03月01日 11:08
需要 登录 后方可回复, 如果你还没有账号请 注册新账号