Ruby:与IRB中未加载的主应用程序文件位于同一目录中的文件

时间:2012-09-04 07:24:09

标签: ruby-on-rails ruby sinatra irb

在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'

它会在哈希中加载所有这些文件/ gem,但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>'

有人可以解释为什么没有正确要求一个文件吗?

1 个答案:

答案 0 :(得分: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__)