简体   繁体   English

我应该在Rails的整个应用程序中使用的计算值存储在哪里?

[英]Where should I store calculated values I use throughout my application in Rails?

I have the following variable definition: 我有以下变量定义:

@monday = (Time.now).at_beginning_of_week

I use that in different models, controllers, and views. 我在不同的模型,控制器和视图中使用它。

Where can I define it (and how should I define it -- @@? ) so I can define it once and use throughout my Rails application? 我在哪里可以定义它(以及应该如何定义它@@?),这样我就可以定义一次并在整个Rails应用程序中使用它?

Should it be in environment.rb? 应该在environment.rb中吗? Should it be a @@? 应该是@@吗?

I would add it to application controller: 我将其添加到应用程序控制器:

before_filter :load_date

def load_date
  @monday =  (Time.now).at_beginning_of_week
end

So it will be accessible in all of yours controllers and views. 因此,它将在您所有的控制器和视图中访问。 If you want to use it in your models, then probably you need it as some param, on example for scopes. 如果要在模型中使用它,则可能需要将其作为一些参数,例如在范围示例中。 Then your controller is place where you should pass this variable to model: 然后,将控制器放置在应将此变量传递给模型的位置:

@models = MyModel.before_date(@monday)

I don't think you need to have only one instance of this variable for whole application. 我认为整个应用程序只需要该变量的一个实例即可。 Initializing it is quite simple. 初始化非常简单。 Also it is not good when you initialize it and don't use it. 当您初始化它并且不使用它时,它也不是一件好事。 For me it is hard to imagine that you need it in all of your controllers and actions. 对我来说,很难想象在所有控制器和动作中都需要它。

The other way is you can define class: 另一种方法是您可以定义类:

class MyDate
  def self.get_monday
    Time.now.at_beginning_of_week
  end
end

And put it in config/initializers (probably there is better place where to put it). 并将其放在config/initializers (可能有更好的放置位置)。 Then you can access it from anywhere in your application: 然后,您可以从应用程序中的任何位置访问它:

MyDate::get_monday

Defining this value using environment.rb is not what you want, because the value would be calculated when the server starts and will remain fixed after that. 不需要使用environment.rb定义此值,因为该值将在服务器启动时进行计算,并在此之后保持不变。 If you want the value to be refreshed every week, this is a problem. 如果您希望每周刷新一次值,这是一个问题。

I would go with the class variable (@@) in ApplicationController. 我将使用ApplicationController中的类变量(@@)。 But this is not accessible in the model. 但这在模型中不可访问。

What you can do is create a new module, define this value in this module, and mixin this module in any controller or model that needs it. 您可以做的是创建一个新模块,在此模块中定义此值,然后在需要该模块的任何控制器或模型中混合该模块。 So you would have MyModule::start_of_week with the value. 因此,您将获得MyModule::start_of_week与值。 Just ensure that this value gets set on every request. 只要确保在每个请求上都设置了该值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM