Ruby on Rails: Where to define global constants?
可能的重復:Ruby on Rails:在哪里定義全局常量?
I am interested in doing this the "Rails Way" on a new application. I would also like to refer to constants in some sort of context to make the code more readable. I have an application where a user can request access to another users's data set. This AccessRequest can have one of the following statuses:
Review Denied Approved
I can see these values being used in reporting features in the future, so I want to make them constants in order to avoid any spelling or capitalization issues. I thought I would just put these in a constants.rb file in the config/initializers directory.
I would like to refer to these as AccessRequest::REVIEW. Since I already have a model called AccessRequest, does it make sense to put them there? Or wrap them in a class in a constants.rb file in the config/initializers directory? Which way is the Rails Way?
You don't need to use constants in Rails 3.It is better to use the Rails::Application singleton.
In your application.rb you can define your constante like:
module Yourapp class Application < Rails::Application config.access_request.review = 'xxx' end end
After in your code you can call
After if you change value in each environment, You just define the config.xx in your
config/environments/production.rb or other environment.
Belated reply, but posting as this answer still comes up in search results. Putting the constant in the model makes sense as the constant pertains directly to it. Using the Rails application config to store constants is incorrect.
As per the comment listed in application.rb:
# Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded