1

在 Sinatra 应用程序中我的主应用程序文件 (tinyclone.rb) 的顶部,此哈希用于需要多个 gem 和一个文件“dirtywords.rb”。脏字文件与 tinyclone.rb 文件位于同一目录中。

%w(rubygems data_mapper sinatra haml dm-core dm-timestamps dm-types uri restclient xmlsimple dirty_words).each  { |lib| require lib}

当我在 irb 中加载 tinyclone.rb 文件时

require '/Users/mm/sites/cloning/tinyclone.rb'

它将所有这些文件/宝石加载到哈希中,除了dirty_words文件

cannot load such file -- dirty_words
    from /Users/mm/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /Users/mm/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /Users/mm/sites/cloning/tinyclone.rb:1:in `block in <top (required)>'
    from /Users/mm/sites/cloning/tinyclone.rb:1:in `each'
    from /Users/mm/sites/cloning/tinyclone.rb:1:in `<top (required)>'
    from /Users/mm/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/mm/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from (irb):1
    from /Users/mm/.rvm/rubies/ruby-1.9.3-rc1/bin/irb:16:in `<main>'

谁能解释为什么没有正确需要一个文件?

4

1 回答 1

1

Ruby 1.9 不包含当前目录到搜索路径中。

有几个选项可以解决这个问题:

# Ruby 1.9 only:
require_relative 'dirty_words'

# Ruby 1.9 and 1.8 compatible:
require File.expand_path('dirty_words', File.dirname(__FILE__))

# Both options above imply that you separate `dirty_words` from the list of libs which
# are present in $LOAD_PATH, and require it separately. Here's another option which
# should allow you to keep require iteration as it is, though it's considered dirty:
$LOAD_PATH << File.dirname(__FILE__)
于 2012-09-04T08:06:43.163 回答