0

I'm a c# programmer and I've recently started working in RoR. I have a controller that retrieves data from an external source (a virtual machine list) and saves it into a variable.

@virtual_machine_list = SomeModule::get_virtual_machines

I have 2 questions regarding this:

  1. the process of getting the list is lengthy, how can i call it only once (similar to a singleton initialization I guess)
  2. how can I retrieve this data (which is not stored in the database) from other Controller's views?

I have several forms and I want to present this list in each one.

1
  • 2
    Why not save it in the database so you have a persistent cache? Saving it in memory is unreliable since Rails processes will be started and retired over the run-time of your application, plus it's common for several to be running at once. They do not share variables or any state not persisted in the user session or some kind of database. Commented Jul 28, 2014 at 15:21

2 Answers 2

1

Just monkey-patch the module and use the ||= memoization technique. It basically assigns to the variable only if it is not present. In both cases, whether it is assigned or not it returns the variable.

module SomeModule
  def self.cached_virtual_machines
    @@cached_virtual_machines ||= self.get_virtual_machines
  end
end
Sign up to request clarification or add additional context in comments.

Comments

1

It sounds like you're wanting to load this data once when your application starts and have it available from all your controllers?

An intializer would be a good fit for this. You could create config/initializers/virtual_machines.rb with the following contents:

Rails.application.config.virtual_machines = SomeModule::get_virtual_machines

then access the value in your controllers from Rails.application.config.virtual_machines.

Note that this does limit you somewhat. Your application will start slower since it needs to load this data every time. If you're running a multi-process configuration in production, that could be an issue. Also, you don't have a way to refresh the data if it's stale.

@tadman's suggestion of putting the data in your database is a decent alternative. Then you can create a cron job that keeps the data refreshed, and have your initializer refresh the database if it's empty or stale.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.