Ruby-on-rails Rails 中的常量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/361247/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:50:41  来源:igfitidea点击:

constant values in Rails

ruby-on-railsrubyconstants

提问by Sarah Vessels

I have some data that I want to store somewhere in my Rails app because I use it for generating form fields, checking a submitted form to ensure its values are valid, etc. Basically, I want the data in one location because I make use of it in several places.

我有一些数据要存储在我的 Rails 应用程序中的某个位置,因为我使用它来生成表单字段、检查提交的表单以确保其值有效等。基本上,我希望将数据放在一个位置,因为我使用它在几个地方。

Previously, I was defining an initializemethod in my controller and initializing instance variables within that method, e.g. @graph_types = ['bar', 'line']. This seemed a bad idea because that's really all initializewas being used for (initializing those values) and the instance variables could be changed later, which I don't want.

以前,我initialize在我的控制器中定义一个方法并在该方法中初始化实例变量,例如@graph_types = ['bar', 'line']. 这似乎是一个坏主意,因为这真的是全部initialize用于(初始化这些值)并且实例变量可以在以后更改,这是我不想要的。

Now, I define constants outside of any method in my controller, right up at the top after my filters, and I freeze them, e.g. GraphTypes = ['bar', 'line'].freeze.

现在,我在控制器中的任何方法之外定义常量,就在过滤器之后的顶部,然后冻结它们,例如GraphTypes = ['bar', 'line'].freeze.

I didn't want to store such data in a config file because then I would have to keep track of an extra file, read in the file and parse it, etc. I didn't want to store this data in the database because that seems like overkill; I don't need to do any crazy LEFT OUTER JOIN-type queries combining available graph types with another of my constants, say Themes = ['Keynote', 'Odeo', '37 Signals', 'Rails Keynote'].freeze. I didn't want to store the data in environment.rb because this data only pertains to a particular controller.

我不想将这些数据存储在配置文件中,因为那样我就必须跟踪一个额外的文件,读入文件并解析它等等。我不想将这些数据存储在数据库中,因为那样看起来有点矫枉过正;我不需要做任何疯狂的 LEFT OUTER JOIN 类型的查询,将可用的图形类型与我的另一个常量相结合,比如Themes = ['Keynote', 'Odeo', '37 Signals', 'Rails Keynote'].freeze. 我不想将数据存储在 environment.rb 中,因为此数据仅与特定控制器有关。

Considering all this, am I going about this 'the Ruby way'?

考虑到所有这些,我是否要采用这种“Ruby 方式”?

采纳答案by J Cooper

I believe what you are currently doing is fine; you said the data only pertains to one controller, and therefore that's where it belongs. If it was needed for multiple controllers, or if they were more complex than constant values, other approaches may make sense.

我相信你目前所做的一切都很好;你说数据只属于一个控制者,因此这就是它所属的地方。如果多个控制器需要它,或者如果它们比常量值更复杂,则其他方法可能有意义。

回答by user37011

For constants that don't really belong anywhere else I have a StaticData class.

对于不真正属于其他任何地方的常量,我有一个 StaticData 类。

  class StaticData

    GRAPH_TYPES = ['bar', 'line']

    SOMETHING_ELSE = ['A', 'B']

  end

Then I get at it with

然后我得到它

StaticData::GRAPH_TYPES

回答by Sasha

The same answer I wrote previously to a similar questionapplies and posting as this answer still comes up in search results.

我之前对类似问题写的相同答案适用并发布,因为该答案仍然出现在搜索结果中。

Putting a constant in the controller makes some sense as the constant pertains directly to it. Constants should otherwise be put in the dedicated initializer file: Rails.root/config/initializers/constants.rb.

将常量放入控制器是有一定意义的,因为常量与其直接相关。否则,常量应该放在专用的初始化文件中:Rails.root/config/initializers/constants.rb.

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 中仍然有效。

回答by Daniel Lucraft

Yes, what you are doing is fine. It's more idiomatic Ruby to call your constant GRAPH_TYPESthough.

是的,你正在做的很好。GRAPH_TYPES不过,将您的常量称为更惯用的 Ruby 。

Incidentally, I would avoid defining initializein your controllers. Seems like it could lead to trouble.

顺便说一句,我会避免initialize在您的控制器中定义。似乎它可能会导致麻烦。

回答by Anthony

I would agree some what with IDBD and paradisepete. Using constants in the model would be the best way to go so that the controller is skinny and the model fat. see Rails view tipsFor example if you had a metrics controller linked to a metric model. In the metric model class Metric < ActiveRecord::Base GRAPHTYPES = ['bar', 'line']

我会同意 IDBD 和天堂之花的一些内容。在模型中使用常量将是最好的方法,这样控制器就会变瘦而模型变胖。请参阅Rails 视图提示。例如,如果您有一个链接到度量模型的度量控制器。在度量模型类 Metric < ActiveRecord::Base GRAPHTYPES = ['bar', 'line']

Then in the view you could do something like

然后在视图中你可以做类似的事情

f.select :graph_type, Metric::GRAPHTYPES

f.select :graph_type, Metric::GRAPHTYPES

回答by IDBD

If you are generating forms that are related to some resource then it will be good variant to store it in the models. You don't need to store it in DB because it can be simple class or instance variables/methods.

如果您正在生成与某些资源相关的表单,那么将其存储在模型中将是一个很好的变体。您不需要将它存储在 DB 中,因为它可以是简单的类或实例变量/方法。

The same idea is for validation. If you are validating resources/model instances then it will be reasonable choice to store validation parameters inside model class.

同样的想法用于验证。如果您正在验证资源/模型实例,那么将验证参数存储在模型类中将是合理的选择。

Anyways, it will be much closer to the 'thick model and thin controller' pattern then any of the variants you mentioned.

无论如何,它将更接近“厚模型和薄控制器”模式,然后是您提到的任何变体。