0

我有一个项目树如下:

├── bin
├── fpgrowth-ruby-0.0.1.gem
├── fpgrowth-ruby.gemspec
├── Gemfile
├── Gemfile.lock
├── lib
│   ├── fpgrowth
│   │   ├── fptree
│   │   │   ├── builder
│   │   │   │   ├── first_pass.rb
│   │   │   │   └── second_pass.rb
│   │   │   ├── fp_tree.rb
│   │   │   └── node.rb
│   │   ├── models
│   │   │   └── transaction.rb
│   │   └── ruby
│   │       └── version.rb
│   └── fpgrowth.rb
├── LICENSE.txt
├── Rakefile
├── README.md
└── test
    └── tc_first_pass.rb

在 first_pass 的测试用例中,我写道:

require 'test/unit'
require "../lib/fpgrowth/fptree/builder/first_pass"

然后我得到这个:

ruby test/tc_first_pass.rb 
/home/damien/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- ../lib/fpgrowth/fptree/builder/first_pass (LoadError)
    from /home/damien/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from test/tc_first_pass.rb:2:in `<main>'

出了点问题,但我不知道是什么。

4

3 回答 3

1

除非您使用require_relative.

除此之外,你应该做的是改变$LOAD_PATH包括../lib.

于 2013-05-23T00:02:51.417 回答
1

在 ruby​​ 命令行上使用 -I 标志,在运行时指定需要的路径。

从您的顶级目录

ruby -I lib test/tc_first_pass.rb

上面告诉 ruby​​ 解释器在加载路径中包含 /lib 仅用于此执行。

然后对于您的要求行,

require 'fpgrowth/fptree/builder/first_pass'

对于 gem 构建和组织你的源代码,我建议阅读关于组织源代码的章节,以及从这里找到的 Programming Ruby 书中分发和打包你的代码:http: //pragprog.com/book/ruby3/programming-ruby-1-9

于 2013-05-23T05:56:46.567 回答
0

您可以使用File类方法来帮助您。

首先是从不相对于 的目录开始cwd,而是相对于调用 require 的文件。他们可能不一样。

require File.dirname(__FILE__) + "../lib/fpgrowth/fptree/builder/first_pass"

join然而,这不是很便携,可以使用类方法来清理:

require File.join(File.dirname(__FILE__), '..', 'lib', 'fpgrowth', 'fptree', 'builder', 'first_pass')

但是您可能会发现自己到处都添加了这个,不是吗?在这种情况下,请考虑在 中添加一个助手fpgrowth.rb

def self.root
  Pathname.new(File.expand_path(File.dirname(__FILE__)))
end

现在,您可以在任何地方使用该助手:

FpGrowth.root #=> "/absolute/path/to/fpgrowth/lib"
FpGrowth.root.join("fpgrowth", "fbtree", "builder") #=> "/absolute/path/to/fpgrowth/lib/fpbrowth/fbtree/builder"
于 2013-05-23T07:54:19.553 回答