[英]Ruby on Rails global array
I want to instantiate an array that is accesible trough all the application, the array may change while the application is running but it will be re-generated when the application starts again. 我想实例化一个可通过所有应用程序访问的数组,该数组可能会在应用程序运行时更改,但在应用程序再次启动时将重新生成。
I have though about putting that array in the ApplicationController but it will die once the request is over or not ?; 我有关于将该数组放在ApplicationController中但是一旦请求结束就会死掉? and I just need it to populate it once every time the app starts running not every time a controller action is called. 每次应用程序开始运行时,我只需要填充一次,而不是每次调用控制器操作时都填充它。
The array is populated from the database and that has to be already loaded. 数组从数据库填充,必须已加载。
Thanks in advance for any guidance. 提前感谢任何指导。
Create a file inside you config/initializers
called whatever-you-want.rb and place you code there. 在config/initializers
创建一个名为whatever-you-want.rb的文件 ,并将代码放在那里。
THIS_IS_AN_ARRAY = [1,2,3,4] THIS_IS_AN_ARRAY = [1,2,3,4]
You should then be able to access THIS_IS_AN_ARRAY
all over your application. 然后,您应该可以在整个应用程序中访问THIS_IS_AN_ARRAY
。
You can create a simple class to keep this information for you. 您可以创建一个简单的类来为您保留此信息。 For example, you can add the following to config/initializers/my_keep.rb: 例如,您可以将以下内容添加到config / initializers / my_keep.rb:
class MyKeep
def self.the_array
@@the_array ||= # Execute the SQL query to populate the array here.
end
def self.add element
if @@the_array
@@the_array << element
else
@@the_array = [element]
end
end
end
In your application, the first time you call MyKeep.the_array
the array will be populated from the database, so you can even do this in the same file or in an after_initialize block in your application.rb file. 在您的应用程序中,第一次调用MyKeep.the_array
,数组将从数据库中填充,因此您甚至可以在application.rb文件的同一文件或after_initialize块中执行此操作。 You'll then be able to add the the array with MyKeep.add(element)
and you'll be able to get the array value with MyKeep.the_array
. 然后,您将能够使用MyKeep.add(element)
添加数组,并且您将能够使用MyKeep.the_array
获取数组值。 This class should not get re-set on every request. 不应该在每个请求上重新设置此类。
You can use a yaml configuration file. 您可以使用yaml配置文件。
See this railscast 看到这个railscast
http://railscasts.com/episodes/85-yaml-configuration-file http://railscasts.com/episodes/85-yaml-configuration-file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.