在 Rails 应用程序中,我将在哪里存储静态/常量值?

问题描述:

我有 rails 应用程序,想知道存储常量的最佳位置?

I have rails app and am wondering the best place to store the constants?

例如:

HELLO_EVERYONE = "hiz"

然后在一些控制器和视图中:

and then in a few controllers and views:

arr_used = [HELLO_EVERYONE]

这取决于您需要访问它们的位置.

It depends on where you need to access them.

如果您需要在整个应用程序中使用它们,您可以将它们放在 environment.rb

If you need to use them throughout your application, you can put them in environment.rb

# environment.rb
#
# other global config info
HELLO_EVERYONE = "hiz"

如果您只需要在特定类中访问它们,您可以在该模型中定义它们.

If you need to access them only inside a specific class, you can define them in that model.

class Test < ActiveRecord::Base
  HELLO_EVERYONE = "hiz"
end

编辑

第二种情况(常量定义在Test类中),也可以在Test类之外访问,只需要引用为测试::HELLO_EVERYONE.

The second case (where the constant is defined in the Test class), can also be accessed outside of the Test class, only it needs to be referenced as Test::HELLO_EVERYONE.

如果您有一个与该对象的域相关的项目列表(如美国州列表),您可能会在视图中使用这些项目(例如 select_tag :address、:state、options_for_select(Address::STATES)).虽然我可能会考虑将其包装在类方法中,而不是暴露类的内部结构.

This may be helpful in cases where you have a list of items relevant to the domain of that object (like a list of US states) that you might use in a view (e.g. select_tag :address, :state, options_for_select(Address::STATES)). Although I might consider wrapping this inside of a class method instead of exposing the internal structure of the class.

class Address< ActiveRecord::Base
  STATES = ["AL", "AK", "AZ", "AR", ...]

  def self.states
    STATES
  end
end