I am using Ruby v1.9.2 and Ruby on Rails v3.2.2. I have many model classes having constant statements. For instance:
# app/models/class_one.rb
class ClassOne < ActiveRecord::Base
CONSTANT_ONE = ClassTwo::CONSTANT_TWO
end
# app/models/class_two.rb
class ClassTwo < ActiveRecord::Base
CONSTANT_TWO = 1
end
When I restart the server, I get the following error:
Routing Error
uninitialized constant ClassTwo::CONSTANT_TWO
Try running rake routes for more information on available routes.
Is the error related to the loading order of files (and so of classes)? How should I solve the problem?
Note: Since Ruby on Rails, I heard that a “working” solution could be to state constants in initializer files (in the config/initializers/ directory). If so, how should that be made the proper way? What do you think about?
Constants in Rails are kind of a pain, as you are beginning to find out. The pain only increases as you really dig in. It is much easier and more maintainable to use an actual method on the class than to use a constant. For example, in testing, it is MUCH easier to modify a method than a constant when covering a variety of use cases. Also, when doing more complicated programming, you can begin to get into loading issues (like multiple loading errors, or unavailability, like you have) that just don’t happen with methods. I’ve stopped using constants in my Rails apps altogether, and haven’t missed them a bit. You may be interested in an article that Advi Grimm wrote to the same effect.
Edit:
If you really desire to use constants, in the way you described, check out Where's the best place to define a constant in a Ruby on Rails application? for more info.