开发者

Where/How to code Constants in Rails 3 Application [duplicate]

开发者 https://www.devze.com 2023-01-18 12:42 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: Ruby on Rails: Where to define global constants?
This question already has answers here: Closed 10 years ago.

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 the开发者_StackOverflow中文版re? 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

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消