Ruby on Rails: Where to define global constants?

I’m just getting started with my first Ruby on Rails webapp. I’ve got a bunch of different models, views, controllers, and so on.

I’m wanting to find a good place to stick definitions of truly global constants, that apply across my whole app. In particular, they apply both in the logic of my models, and in the decisions taken in my views. I cannot find any DRY place to put these definitions where they’re available both to all my models and also in all my views.

To take a specific example, I want a constant COLOURS = ['white', 'blue', 'black', 'red', 'green']. This is used all over the place, in both models and views. Where can I define it in just one place so that it’s accessible?

What I’ve tried:

  • Constant class variables in the model.rb file that they’re most associated with, such as @@COLOURS = [...]. But I couldn’t find a sane way to define it so that I can write in my views Card.COLOURS rather than something kludgy like Card.first.COLOURS.
  • A method on the model, something like def colours ['white',...] end – same problem.
  • A method in application_helper.rb – this is what I’m doing so far, but the helpers are only accessible in views, not in models
  • I think I might have tried something in application.rb or environment.rb, but those don’t really seem right (and they don’t seem to work either)

Is there just no way to define anything to be accessible both from models and from views? I mean, I know models and views should be separate, but surely in some domains there’ll be times they need to refer to the same domain-specific knowledge?

13 Answers
13

Leave a Comment