Rails snippet: require app files only once

Ruby’s Kernel.require method will re-require the same source file if you pass it differing arguments that point to the same file. It doesn’t use File.expand_path to make sure it hasn’t already loaded the same file before. This can cause problems if you’re using constants or doing one-time initialization in a source file that’s getting loaded multiple times for one reason; you’ll need to add a wrapper that prevents re-entry.

If this annoys you as much as it does me (why should my application code include workarounds for what I regard to be a Ruby bug?), add this snippet to your config/environment.rb (pre Rails 2.0) or config/preinitializer.rb (Rails 2.0 or later).

The is_app_file check may not be the best way to test for it; I can see how if you fiddle with $: so that the current directory files load after some other directory, you might load things in the wrong order. Please post fixes if you find this to be a real problem and have an idea of how to fix it.

2 thoughts on “Rails snippet: require app files only once”

Leave a Reply

Your email address will not be published. Required fields are marked *