It depends which Ruby version you are using.
In 1.8, it should work as you do. In 1.9 you should use require_relative
.
You should also not add '.rb' at the end, this is not recommended.
The danger with a simple 'require' with a relative path is if this script is itself required by another, then the path will be relative to the first script called:
rootdir
- main.rb
- subdir1
- second.rb
- subdir11
- third.rb
If main.rb is called, and then require second.rb (with 'subdir1/second'
), and then you want to require third.rb with 'subdir11/third.rb'
, it will not work.
You could be relative to the first script (subdir1/subdir11/third.rb
), but that is not a good idea.
You could use __FILE__
and then make it an absolute path:
require File.expand_path('../subdir11/third.rb', FILE)
(the first .. is to get in the directory which contains the file) or
require File.dirname(FILE) + '/subdir11/third.rb'
But the most common practice is to reference it from the rootdir.
In a gem, you can assume the rootdir will be in the $LOAD_PATH
(or you can add it yourself).
In Rails you can use require "#{RAILS_ROOT}/path"
(rails2) or
require Rails.root.join('path')
(rails3)