Where is the best place to define a constant in a Ruby on Rails application?

In a Ruby on Rails application, where is the best place to define a constant?

I have an array of persistent data that I need for all the controllers in my application.

+43
ruby ruby-on-rails constants
Jul 10 '09 at 5:02
source share
2 answers

Rails> = 3, the application itself is a module (lives in config/application.rb ). They can be saved in the application module.

 module MyApplication SUPER_SECRET_TOKEN = "123456" end 

Then use MyApplication::SUPER_SECRET_TOKEN to refer to the constant.




Rails> = 2.1 && <3 you must put them

  • in /config/initializers when the constant has an application scope
  • when a constant refers to a specific model / controller / helper, you can cover it inside the class / module itself



Prior to Rails 2.1 and initializers programmers were used to place application constants in environment.rb.

Here are some examples.

 # config/initializers/constants.rb SUPER_SECRET_TOKEN = "123456" # helpers/application_helper.rb module ApplicationHelper THUMBNAIL_SIZE= "100x20" def thumbnail_tag(source, options = {}) image_tag(source, options.merge(:size => THUMBNAIL_SIZE) end end 
+63
Jul 10 '09 at 6:52
source share

You can put them in config / environment.rb:

 Rails::Initializer.run do |config| ... SITE_NAME = 'example.com' end 

If you have a large number of global constants, this can be messy. Browse the sources from the YAML file or save the constants in the database.

EDIT:

Answer

weppos is the best answer.

Save the constants in a file in config / initializers / *. rb

+10
Jul 10 '09 at 5:07
source share



All Articles