查看了相关 active_support 关于 autoload 的相关解释和源码,然后自己试着用一下这个方法:
文件目录结构如下
demo/
| - main/
| | - base.rb
| | - scoping.rb
| - main.rb
| - run.rb
代码如下:
#main.rb
require 'active_support/all'
ActiveSupport::Dependencies.autoload_paths.push('.', 'main')
module Main
extend ActiveSupport::Autoload
autoload :Base
autoload :Scoping
end
#main/base.rb
module Main
class Base
include Scoping
end
end
# main/scoping.rb
module Main
module Scoping
def hello
"hello world"
end
end
end
# run.rb
require 'main'
b = Main::Base.new
p b.hello
当我在运行 ruby run.rb 时报错,提示信息为:
Traceback (most recent call last):
7: from run.rb:1:in `<main>'
6: from run.rb:1:in `require_relative'
5: from main.rb:19:in `<top (required)>'
4: from /usr/local/lib/ruby/gems/2.6.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `require'
3: from /usr/local/lib/ruby/gems/2.6.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:257:in `load_dependency'
2: from /usr/local/lib/ruby/gems/2.6.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `block in require'
1: from /usr/local/lib/ruby/site_ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/usr/local/lib/ruby/site_ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- main/base (LoadError)
我的理解是在 main.rb 中使用 ActiveSupport::Dependencies.autoload_paths.push('.', 'main') 将目录添加至 autoload_path 中,则使用 autoload 方法后,会在需要时自动加载 base.rb 和 scoping.rb。但是实际却加载失败了,请问是我理解错误,还是代码表达的时候写错了。该如何修正?