一直对这个问题比较疑惑,根据 ruby api 的介绍,如果”xx“是绝对路径,则从绝对路径中查找,如果是相对路径,则会去$LOAD_PATH 中查找。我在自己的本地文件建立文件夹 test,test 文件夹的中存在两个文件,分别是 redflag.rb 文件和 test_events.rb 文件,文件内容分别如下:
#redflag.rb
def event(name)
puts "ALTER: #{name}" if yield
end
Dir.glob("*events.rb").each{ |file| load file}
#test_events.rb
event "an event that always happens" do
true
end
event "an event that never happens" do
false
end
#终端执行文件,ruby reflag.rb
ALTER: an event that always happens
如上代码叙述,正确 load 了文件,并且执行了相关的代码。
test 文件夹的目录为:
/Users/jayzen/workshop/dsl
puts $LOAD_PATH 的结果为:
/Users/jayzen/.rvm/gems/ruby-2.4.0@global/gems/did_you_mean-1.1.0/lib
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/x86_64-darwin16
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/vendor_ruby/2.4.0
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/vendor_ruby/2.4.0/x86_64-darwin16
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/vendor_ruby
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0
/Users/jayzen/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/x86_64-darwin16
从上面可知,load 的文件是相对目录,但是$LOAD_PATH 中并没有包括 test 的文件夹路径,那么 load 的真正加载路径是什么?