Ruby如何知道在哪里可以找到所需的文件? [英] How does Ruby know where to find a required file?
问题描述
这里是另一个新手问题:
Here is one more newbie question:
require 'tasks/rails'
我在每个rails项目的根路径中的Rakefile中看到了这一行.我猜这行是用来要求vendor/rails/railties/lib/tasks/rails.rb加载所有rake任务的:
I saw this line in Rakefile in the root path of every rails project. I guess this line is used to require vendor/rails/railties/lib/tasks/rails.rb to get all rake tasks loaded:
$VERBOSE = nil
# Load Rails rakefile extensions
Dir["#{File.dirname(__FILE__)}/*.rake"].each { |ext| load ext }
# Load any custom rakefile extensions
Dir["#{RAILS_ROOT}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
Dir["#{RAILS_ROOT}/vendor/plugins/*/**/tasks/**/*.rake"].sort.each { |ext| load ext }
我的问题是为什么只为require方法指定任务/轨道",而不为文件的完整路径指定?
My question is why only 'tasks/rails' is specified for the require method, but not the full path of the file?
谢谢.
推荐答案
在启动Rails应用程序时,它会运行config/boot.rb并调用
When you start your rails app it runs config/boot.rb which calls Rails::Initializer.set_load_path
and thatsets up the $LOAD_PATH
.
Ruby使用该目录列表查找在require
行上指定的文件.如果您给它一个像require '/home/lolindrath/ruby/lib.rb'
这样的绝对路径,它将跳过该搜索.
Ruby uses that list of directories to find the files specified on a require
line. If you give it an absolute path like require '/home/lolindrath/ruby/lib.rb'
it will skip that search.
这与C/C ++中的#include <stdlib.h>
大致相似,在C/C ++中,它搜索您为编译器提供的包含路径以找到该头文件.
This is roughly analogous to #include <stdlib.h>
in C/C++ where it searches the include path you give the compiler to find that header file.
这篇关于Ruby如何知道在哪里可以找到所需的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!