我正在尝试请求一个我在另一个文件中创建的 rake 文件。这两个文件位于两个不同的目录中。我在第一个文件的顶部有 require,在 require 之后的引号内有第二个文件的名称。 它告诉我它无法加载这样的文件。 这是否意味着因为它在不同的目录中找不到它? 我尝试坚持第二个文件的完整路径,但它仍然无法加载文件。 有谁知道如何将第二个文件加载到第一个文件中?
提前致谢
最佳答案
require
将仅在一组称为“加载路径”的位置中搜索文件。您可以在脚本或 irb session 中使用全局变量 $LOAD_PATH
查看加载路径。如果它不在加载路径中,则不会找到它。
Ruby 1.9 引入了 require_relative
,它使用当前文件的位置作为起点进行搜索。
# Will search $LOAD_PATH for file.
require 'test/unit'
# Notice the '/' which tells it to look in the
# 'test' folder for a file named 'unit.rb'
# Will look in current folder of file
require_relative 'my_folder/my_file'
# Will search in 'my_folder' for the file 'my_file.rb'
请注意,require_relative
在 irb 中不起作用。
另请注意,如果您真的想使用 require
,您可以通过向 $LOAD_PATH
变量添加一个位置来启动您的脚本。
$LOAD_PATH << File.join('users', 'yourusername', 'your_folder')
# or
$LOAD_PATH << File.dirname(__FILE__)
# The second one enables you to move the file around on your
# system and still operate correctly
require 'my_file'
这是来自 Ruby-Doc 的一些附加文档:
关于ruby-on-rails - 如何从另一个目录中获取 ruby 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16856243/