在 Ruby on Rails 应用程序中定义常量的最佳位置在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1107782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where's the best place to define a constant in a Ruby on Rails application?
提问by mlambie
In a Ruby on Rails application, where is the best place to define a constant?
在 Ruby on Rails 应用程序中,定义常量的最佳位置在哪里?
I have an array of constant data that I need available across all the controllers in my application.
我有一组常量数据,我需要在我的应用程序中的所有控制器中使用这些数据。
回答by Simone Carletti
Rails >= 3, the application is itself a module (living in config/application.rb). You can store them in the application module
Rails >= 3,应用程序本身就是一个模块(住在 中config/application.rb)。您可以将它们存储在应用程序模块中
module MyApplication
SUPER_SECRET_TOKEN = "123456"
end
Then use MyApplication::SUPER_SECRET_TOKENto reference the constant.
然后使用MyApplication::SUPER_SECRET_TOKEN引用常量。
Rails >= 2.1 && < 3 you should place them
Rails >= 2.1 && < 3 你应该放置它们
- in
/config/initializerswhen the constant has the applications scope - when the constant refers to a specific model/controller/helper you can scope it within the class/module itself
- 在
/config/initializers常量具有应用范围时 - 当常量引用特定的模型/控制器/帮助程序时,您可以将其范围限定在类/模块本身内
Prior to Rails 2.1 and initializerssupport, programmers were used to place application constants in environment.rb.
在 Rails 2.1 和initializers支持之前,程序员习惯于在 environment.rb 中放置应用程序常量。
Here's a few 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
回答by guns
You can place them in config/environment.rb:
您可以将它们放在 config/environment.rb 中:
Rails::Initializer.run do |config|
...
SITE_NAME = 'example.com'
end
If you have large amounts of global constants, this can be messy. Consider sourcing from a YAML file, or keeping the constants in the database.
如果您有大量全局常量,这可能会很混乱。考虑从 YAML 文件中获取资源,或将常量保存在数据库中。
EDIT:
编辑:
weppos' answer is the better answer.
weppos 的答案是更好的答案。
Keep your constants in a file in config/initializers/*.rb
将常量保存在 config/initializers/*.rb 文件中

