I ran into the following problem in my application when I went from my
dev environment to my staging environment. Modules and classes that
were previously autoloaded just fine in dev ended up with a strange
error in staging:
NameError: uninitialized constant Rails::Initializer::…
Weird.
Well, I managed to reproduce it, and here is the procedure. I’m
wondering if the approach I’m using to setup environment-specific
values for these constants is the culprit, and maybe there’s a better
way. Or maybe this is some sort of wacky bug? Anyway, here’s the
procedure. Let me know what you think.
—>8— cut here —>8—
-
Create a new Rails app, e. g. $ rails constant
-
Edit the environment.rb file to add your own module with
configuration constant default values with the idea you could
“override” these by specifying them in the specific environment file:
At the end of config/environment.rb, add:
module AppConstants
IMPORTANT_VALUE = “x” unless defined?(AppConstants::IMPORTANT_VALUE)
end
- Create a Ruby module in the file lib/app_constants/list.rb, noting
the “top level” name of the module matches the one specified in the
environment file:
module AppConstants
module List
LIST_CONSTANT = “list_constant”
end
end
- Fire up the console and probe the constant values:
Loading development environment.
AppConstants::List::LIST_CONSTANT
=> “list_constant”AppConstants::IMPORTANT_VALUE
=> “x”
- Quit from the console and add development-specific value for the
constant defined in the environment file:
At the end of config/environments/development.rb, add:
module AppConstants
IMPORTANT_VALUE = “definitely_not_x”
end
- Fire up the console again and probe the constant values:
Loading development environment.
AppConstants::List::LIST_CONSTANT
NameError: uninitialized constant
Rails::Initializer::AppConstants::List
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/
active_support/dependencies.rb:263:inload_missing_constant' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/ active_support/dependencies.rb:452:in
const_missing’
from (irb):1AppConstants::IMPORTANT_VALUE
=> “definitely_not_x”AppConstants::List::LIST_CONSTANT
NameError: uninitialized constant
Rails::Initializer::AppConstants::List
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/
active_support/dependencies.rb:263:inload_missing_constant' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/ active_support/dependencies.rb:452:in
const_missing’
from (irb):3