Rails 6: How to load global variables only once?

Viewed 483

My app uses global variables like logos, app name, etc retrieved from the database and shown on different controllers and views. I put it in ApplicationController to be available to all, but I find that the individual controllers repeat the same query sometimes.

class ApplicationController < ActionController::Base
  $image = Setting.find_by_name('image').value
  $city = Setting.find_by_name('city').value
  $currency = Setting.find_by_name('currency').value 
end

Is there a way to make the same variables available to all controllers (and users) with just a one-time query with the variables saved on memory, such as when the app starts up?

2 Answers

You could attempt to use initializers.

Rail will load all files in config/initializers/ folder when the server starts up. This can work as a place to initialize application-wide variables. We could create a file inventory.rb file in the initializers directory: at config/initializers/inventory.rb

module Inventory
  class Count
    Orders = Order.all
  end
end

Inventory::Count::Orders
# =>  "[your orders will show here]"

These will only be loaded once when the server is started or restarted. As such this works well if the values you need won't change. If they will change I don't think there is a good way to avoid running multiple queries.

Related