RAILS_ROOT and Dir.chdir 1
It's been awhile since I've blogged on Rails, got diverted to a Novell to Windows conversion over Christmas break. A local community college requested emergency assistance with completing their conversion and asked us to do it in 2 weeks. My team and I got it done but it was a hell of a lot of work. Now that I'm back to programming, I ran into a little annoyance last night that took awhile to troubleshoot down. I'm working on a little app to provide a web interface to my book collection. My book repository is located elsewhere on my harddrive so I used Dir.chdir to move to the root of the repository.
To make a long story short, DO NOT use Dir.chdir in your Rails Applications. RAILS_ROOT, which is used to locate dependencies is a relative path. If you change the working directory of your Rails application, Rails may/will have problems loading dependencies. In my case, I used Dir.chdir to move to then iterate the publisher directories and add books found onto the publisher.books has_many association. This promptly failed with Publisher::Book uninitialized constant errors. The dependency loading mechanism uses RAILS_ROOT to find items in your load_paths and being a relative path, changes if you change the current working directory.
I believe one solution, which I didn't test, would be to set RAILS_ROOT to an absolute path in your environment.rb. The solution I chose was to not chdir but use a full path in each Directory or File operation i used. And now you know.
Comments
-
I had the same problem - I was building a Ferret search index in a controller (I believe Ferret is doing Dir.chdir at some point) and afterwards ror couldn't compile/resolve the *.rhtml files anymore... My solution was to set the RAILS_ROOT in environment.rb. It does the job for now.