user2422461
user2422461

Reputation: 25

Accessing data from another controller in Rails

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.

Upvotes: 0

Views: 383

Answers (2)

James Mason
James Mason

Reputation: 4296

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.

Upvotes: 1

hahcho
hahcho

Reputation: 1409

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

Upvotes: 1

Related Questions