Where/How to code Constants in Rails 3 Application

2020-02-07 16:39发布

Possible Duplicate:
Ruby on Rails: Where to define global constants?

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?

2条回答
贼婆χ
2楼-- · 2020-02-07 17:12

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

Yourapp::Application.config.access_request.review

After if you change value in each environment, You just define the config.xx in your config/environments/production.rb or other environment.

查看更多
▲ chillily
3楼-- · 2020-02-07 17:31

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

This is still valid as of Rails 3.

查看更多
登录 后发表回答