14

In Rails, where should I define the variable which can be recognized by every layer of Rails stacks.

For example, I would like to have a CUSTOMER_NAME='John' variable which can be accessed in helper, rake task, controller and model. Where should I define this variable in Rails app?

I am using Rails v2.3.2

Mark Huk
  • 2,379
  • 21
  • 28
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • What you are asking about is not variable, but a constant, what means: it cannot be set from within application. I was misleaded here by search engine because the wrong term is used here. – Paul May 27 '14 at 12:05

3 Answers3

15

In an initializer in /app/config/initializers all .rb files in here get loaded, I usually create one called preferences.rb for things like this.

See: http://guides.rubyonrails.org/configuring.html#using-initializer-files

Paul Groves
  • 3,983
  • 2
  • 23
  • 24
15

An alternative approach is to set a key on the config object in config/application.rb, like so:

MyApp::Application.configure do
   # ...
   config.my_key = 'some "global" value'
end

You can then access my_key from anywhere in your app with just this:

MyApp::Application.config.my_key

Also, Mike Perham has described a similar, though a more comprehensive approach in his blog post.

Marek Příhoda
  • 11,108
  • 3
  • 39
  • 53
9

You want a true global constant? Use ::COSTUMER_NAME. You want a true global variable? Use $COSTUMER_NAME (discouraged). You want a request-global variable? Use the Hash in the #env method.

Reactormonk
  • 21,472
  • 14
  • 74
  • 123