I am using Ruby on Rails 3.1 and I would like to understand how to solve the following issue in the right way when I state constants.
I have 2 classes:
class Class1 < ActiveRecord::Base
CONSTANT_CLASS_1_A = Class2::CONSTANT_CLASS_2_A # => 222
CONSTANT_CLASS_1_B = 111
end
class Class2 < ActiveRecord::Base
CONSTANT_CLASS_2_A = 222
CONSTANT_CLASS_2_B = Class1::CONSTANT_CLASS_1_B # => 111
end
When I try to “use”/”load” the Class1 I get the following error:
NameError in ...
uninitialized constant Class1::CONSTANT_CLASS_2_B
However, if I state the below code (note the constant statement order) it will work:
class Class1 < ActiveRecord::Base
CONSTANT_CLASS_1_B = 1
CONSTANT_CLASS_1_A = CONSTANT_CLASS_2_A * CONSTANT_CLASS_3_B # => 3
end
I know that I can state the CONSTANT_CLASS_1_B before the CONSTANT_CLASS_1_B (at least to “solve” the problem at this time), but is it correct? That is, is there a way to solve my issue in a “right” and “performant” way (for example, loading all Class1 constants before to retrieve other constants)? Is it advisable to use the above code?
Bonus: There is a convention for this kind of issues? If so, what is it?
The right way to do this is probably have just one constant referencing the data you’re looking for. Doubling up definitions leads to problems like this and additionally will make your code hard to read and understand.
If there isn’t a really compelling reason to have the same constant in two places — and there almost never is — don’t define CONSTANT_CLASS_2_B or CONSTANT_CLASS_1_A. If you want them, reference them from the other model like this: