This post originated from an RSS feed registered with Ruby Buzz
by Bob Silva.
Original Post: RAILS_ROOT and Dir.chdir
Feed Title: Rails Video Tutorials
Feed URL: http://www.railtie.net/xml/rss/feed.xml
Feed Description: A growing collection of screencasts that show you how to use the many facets of the wonderful world of rails.
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.