问题描述
在Ruby on Rails应用程序中,定义常量的最佳位置在哪里?
In a Ruby on Rails application, where is the best place to define a constant?
我有一个数组常量,需要在所有控制器上使用在我的应用程序中。
I have an array of constant data that I need available across all the controllers in my application.
推荐答案
Rails> = 3,该应用程序本身就是一个模块(位于 config中/application.rb
)。您可以将它们存储在应用程序模块中
Rails >= 3, the application is itself a module (living in config/application.rb
). You can store them in the application module
module MyApplication
SUPER_SECRET_TOKEN = "123456"
end
然后使用 MyApplication :: SUPER_SECRET_TOKEN
引用常量
Rails> = 2.1&& < 3您应该将它们
Rails >= 2.1 && < 3 you should place them
- 放置在
/ config / initializers
中,应用程序作用域 - 当常量引用特定模型/控制器/帮助器时,您可以在类/模块本身中作用域
- in
/config/initializers
when 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
在Rails 2.1和 initializers
支持之前,程序员习惯于将应用程序常量放置在环境中。 rb。
Prior to Rails 2.1 and initializers
support, programmers were used to place application constants in environment.rb.
以下是一些示例
# 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
这篇关于在Ruby on Rails应用程序中定义常量的最佳位置在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!