开发者

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 i开发者_开发知识库n the ApplicationController but it will die once the request is over or not ?; 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.

THIS_IS_AN_ARRAY = [1,2,3,4]

You should then be able to access THIS_IS_AN_ARRAY all over your application.


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:

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. 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. This class should not get re-set on every request.


You can use a yaml configuration file.

See this railscast

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜