2016-09-28 121 views
3

我有一个看起来像这样的目录结构:红宝石'需要':无法加载这样的文件(LoadError)

- lib 
    - yp-crawler (directory) 
     - file-a.rb 
     - file-b.rb 
     - file-c.rb 
    - yp-crawler.rb 

lib/yp-crawler.rb文件看起来像这样:

require "yp-crawler/file-c" 
require "yp-crawler/file-b" 
require "yp-crawler/file-a" 

module YPCrawler 
end 

当我尝试通过这样做,我跑在命令行文件:

ruby lib/yp-crawler.rb 

我得到这个错误:

`require': cannot load such file -- yp-crawler/file-c (LoadError) 
    from .rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' 
    from lib/yp-crawler.rb:1:in `<main>' 

什么可能导致这种情况?

+1

你尝试过'require_relative'文件吗?'“? – davidhu2000

+1

@ davidhu2000布鲁夫......完美。这工作。添加它作为答案,我会接受。谢谢! – marcamillion

回答

2

根据API Dock,require_relative是您所需要的。

Ruby tries to load the library named string relative to the requiring file’s path. If the file’s path cannot be determined a LoadError is raised. If a file is loaded true is returned and false otherwise.

因此,所有你需要做的就是

require_relative "file-a" 
require_relative "file-b" 
require_relative "file-c" 
+0

出于好奇,这是1.8/1.9以来的新变化吗? – marcamillion

3

你可以做的另一件事是将目录添加到$LOAD_PATH(这是怎么了大部分的宝石需要的文件)。
$LOAD_PATH(又名$:)是您在拨打require时查找文件的位置。

所以,你可以试试这个代码

# lib/yp-crawler.rb 

$LOAD_PATH.unshift File.expand_path('..', __FILE__) 
# it can be $LOAD_PATH.push also 

require "yp-crawler/file-c" 
require "yp-crawler/file-b" 
require "yp-crawler/file-a" 

module YPCrawler 
end 

附: 例如,您可以see paperclip如何做同样的事情。

+1

我只是想发布这个。 – engineersmnky

相关问题