Constant crisis

In my Rails application, I have a file in

RAILS_ROOT/lib/pcm/web_services/constants.rb

On my development machine (OS X), I am able to reference items in this file/module using the prefix “PCM::WebServices::Constants” without having to require the file. Once deployed on Linux, however, this approach broke and I had to explicitly

require 'pcm/web_services/constants'

(or any other file I needed from the lib/pcm directory) for things to work. I suspected it had something to do with case sensitivity on Linux as opposed to not-so-case-sensitivity on OS X. I was wrong.

Upon further investigation, I find I can easily reproduce the problem, although I do not yet have an explanation.  The solution to the problems are (so far):

1) Explicitly require ‘pcm/web_services/constant’ wherever I need it.  No biggie, but I prefer the “less is more” philosophy where Rails automagically loads the constant without the explicit require.

More possible solutions coming soon…

—>8— cut here —>8—

1) Create a new Rails app, e. g. $ rails constant

2) 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

3) 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

3) Fire up the console and probe the constant values:

Loading development environment.

>> AppConstants::List::LIST_CONSTANT
=> "list_constant"
>> AppConstants::IMPORTANT_VALUE
=> "x"

4) 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

5) 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:in `load_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):1
>> AppConstants::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:in `load_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

Leave a Reply