Where to put constants

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.

Just a question of best practice. Any commetns?

Pito wrote:

Just a question of best practice. Any commetns?

you can put them in your config/environment.rb file

VEHICULAR_TYPES = {:CAR => 1, :BOAT => 2} # non-oo type specifications
to support db operations

or you can stick them in any appropriate model above the class
definition

hth

ilan

On 17 Jan 2008, at 21:12, Pito wrote:

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.

They will be available elsewhere, you just need to say Vehicle::CAR

Fred

Is there really a need to store the number on the field; Are you
supporting
a legacy system as well as a new system?

If not, why not just store “car” or “boat” on the field. Even better
would
be to have a vehicle types table. When you want to add more vehicle
types
then you’ll have to update this table and not the constant.

On Jan 18, 2008 7:51 AM, Ilan B. [email protected]
wrote:


Ryan B.

Feel free to add me to MSN and/or GTalk as this email.

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.

I’m just saying…

///ark