I have a column in my database which is a code, kind of a record
type.
For example, in model Vehicle, I use a 1 for CAR and a 2 for BOAT in
the database.
I want to have constants accessible so that the mapping to 1 and 2 is
in only one place.
So I created constants:
CAR = 1
BOAT = 2
Question is, where to put these.
If I put then in the Vehicle model then they are available only there
and I need them elsewhere, if no-where else, then in my rspec tests.
But also, I use them in the interface of other classes, for example I
might have a Dealer model which has_many :vehicles. And I might want
to have a find_all(vehicle_type) method on Dealer which now needs
those constants too.
So now I have them in config/initializers but I am not sure that this
is an appropriate use of that. After all in a way CAR and BOAT are
parts of the Vehicle model and should live only there. On the other
hand they are also part of the public interface and are used elsewhere
too.
Yet another solution is to use inheritance. This would work best with
a limited number of types. I'm not necessarily advocating this
approach, but I would say two things:
1) This approach would let Rails take care of guaranteeing that your
model constants match your database constants.
2) It actually would be object-oriented at the same time, since a Car
is-a Vehicle.