其中/如何在Rails 3應用程序中編碼常量[duplicate]

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


Possible Duplicate:
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:

我對在新應用程序上使用“Rails方式”進行此操作很感興趣。我還想在某種上下文中引用常量,以使代碼更具可讀性。我有一個應用程序,用戶可以請求訪問另一個用戶的數據集。

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.

我可以看到這些值將在將來的報表特性中使用,因此我希望使它們成為常量,以避免出現任何拼寫或大小寫問題。我想把它們放在一個常量里。配置/初始化器目錄中的rb文件。

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?

我想把它們稱為AccessRequest::REVIEW。既然我已經有了一個叫做AccessRequest的模型,把它們放在那里有意義嗎?或者將它們封裝到一個常量類中。配置/初始化器目錄中的rb文件?哪條路是軌道?

2 个解决方案

#1


42  

You don't need to use constants in Rails 3.It is better to use the Rails::Application singleton.

您不需要在Rails 3中使用常量。最好使用Rails::應用程序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.

如果您在每個環境中更改值,您只需定義配置。你的配置/環境/生產xx。rb或其他環境。

#2


28  

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.

遲來的回復,但在搜索結果中仍然會出現這個答案。將常數放入模型中是有意義的,因為常數直接屬於它。使用Rails應用程序配置來存儲常量是不正確的。

As per the comment listed in application.rb:

根據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.

這在Rails 3中仍然有效。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/10/04/32ae6c07dbfe42d29b6405855261a363.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com