Ruby on Rails Global Array

I want to create an instance of an array accessible through the entire application, the array may change while the application is running, but it will be generated when the application is restarted.

I have a question about placing this array in ApplicationController, but will it die after the request is complete or not ?; and I just need to fill it every time the application does not start every time the controller action is called.

The array is populated from the database and should already be loaded.

Thanks in advance for any recommendations.

+4
source share
3 answers

You can create a simple class to store this information for you. For example, you can add the following to 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 MyKeep.the_array call MyKeep.the_array array will be populated from the database, so you can do this in the same file or in the after_initialize block in the application.rb file. Then you can add the array using MyKeep.add(element) , and you can get the value of the array using MyKeep.the_array . This class should not be reinstalled on every request.

+4
source

Create a file inside config/initializers called any-you-want.rb and place the code there.

THIS_IS_AN_ARRAY = [1,2,3,4]

Then you can access THIS_IS_AN_ARRAY throughout your application.

+5
source

You can use yaml configuration file.

Watch this railscast

http://railscasts.com/episodes/85-yaml-configuration-file

+1
source

Source: https://habr.com/ru/post/1344139/


All Articles