Rack does indeed change the working directory to /
when run as a daemon.
In Ruby 1.8.7, __FILE__
in a required file refers to the path used to load the file, which could be a relative path from the current working directory of the process. However this value is not updated if the working directory is later changed, e.g. with a call to Dir.chdir
.
File.expand_path
expands relative files paths relative to the working directory. So in this case File.expand_path(__FILE__)
results in the paths relative to the root, but the value of __FILE__
is relative to the original working directory, giving the wrong result.
In Ruby 1.9.2 and 1.9.3, __FILE__
in a required file refers to the absolute path of the file, so this problem doesn’t arise.
One way to fix this in Ruby 1.8.7 is to use an absolute path when requiring your application file. Change the line require 'test.rb'
in your config.ru
to:
require File.expand_path('../test', __FILE__)
Now the references to __FILE__
will be absolute, so won’t be affected by the change in working directory when daemonising.
If your application is more complicated, with more files, it might be better to set up your load path instead. For example your could put all your .rb
files into a lib/
directory, then in your config.ru
add:
$LOAD_PATH.unshift(File.expand_path '../lib', __FILE__)
You can then just require your files without worrying about the relative paths.