views:

33

answers:

1

I have a file at lib directory in my rails project. like this a (directory) a1 a2 a.rb

when I in a.rb require a1.

require 'a/a1'

it will warn me /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- a/a1 (MissingSourceFile)

but use dirname(FILE), it work.

require File.dirname(__FILE__) + '/a/a1

why?

+1  A: 

The code:

requie 'a/a1'

will try to find the directory a from the current working directory, which may not be what you think, especially if executing from an environment other than the command line (rails console, or textmate for example).

require File.dirname(__FILE__) + '/a/a1

appends '/a/a1 to the path of the file in which that line appears, so you are sure of always getting the right file, whichever environment you're operating in.

stephenr