Rails ActiveSupport::Autoload 中的一点疑惑

ane · 2014年11月25日 · 最后由 naitnix 回复于 2015年12月11日 · 3056 次阅读

刚刚跟踪代码的时候,恰好看到了 ActiveSupport::Autoload 里面的一个奇怪的地方,

github 地址https://github.com/rails/rails/blob/master/activesupport/lib/active_support/dependencies/autoload.rb 37 行

def autoload(const_name, path = @_at_path)
  unless path
    full = [name, @_under_path, const_name.to_s].compact.join("::")
    path = Inflector.underscore(full)
  end

  if @_eager_autoload
    @_autoloads[const_name] = path
  end

  super const_name, path
end

代码里的这行full = [name, @_under_path, const_name.to_s].compact.join("::")中的这个 name 变量是那里来的?找半天也没发现个所以然。

name 是当前 class 的 name Object.name

一般不知名的 没有@的变量 基本上都是 self.xxx

#3 楼 @zj0713001 哦,酱紫,还是意识有点差,就觉得是个局部变量

#4 楼 @ane binding 进去输出一下就行了 gem 的源码里面也是可以打断点的 只要整个项目启动的时候加载了 debug 工具

#5 楼 @zj0713001 我看了下测试,不是Object.nameActiveSupport::Autoload.name # "ActiveSupport::Autoload",但是我不会 binding,不知道 binding 意思

module MyLib
  extend ActiveSupport::Autoload
  autoload :Model

  eager_autoload do
    autoload :Cache
  end
end
MyLib.name # => "MyLib"
test "the location of autoloaded constants defaults to :name.underscore" do
  module ::Fixtures::Autoload
    autoload :SomeClass
  end

  assert !$LOADED_FEATURES.include?(@some_class_path)
  assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end

test "the location of :eager autoloaded constants defaults to :name.underscore" do
  module ::Fixtures::Autoload
    eager_autoload do
      autoload :SomeClass
    end
  end

  assert !$LOADED_FEATURES.include?(@some_class_path)
  ::Fixtures::Autoload.eager_load!
  assert $LOADED_FEATURES.include?(@some_class_path)
  assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
end

Module.name #=> Returns the name of the module mod. Returns nil for anonymous modules.

需要 登录 后方可回复, 如果你还没有账号请 注册新账号