Jason Varga
Jason Varga

Reputation: 1959

Saving a database query to a variable

I've set up a simple 'Settings' model so I can create some user-modifiable globals which I can use throughout my app. This model has var_name and value columns. The var_name is a primary key.

I can access these using Setting.find('my_variable_name'), which works, but results in a database query every time.

I'd like to be able to 'cache' the settings once, instead of querying the db every time.
I'm not sure of the correct way to go about this, I'm still new to Rails.

I imagine something like settings = Setting.all in my application controller to put all the settings in a variable, then create a way to manipulate a single variable out of it - call it using something like settings.my_variable_name...
...But I don't know how :)

Any advice would be appreciated. Thanks.

Upvotes: 2

Views: 1784

Answers (1)

Sam
Sam

Reputation: 3067

Try adding this to your Setting model,

class Setting < ActiveRecord::Base
  def self.fetch(name)
    fetch_all.detect { |s| s.var_name == name }
  end

  def self.fetch_all
    @fetch_all ||= Setting.all
  end

  def self.reload_all!
    @fetch_all = Setting.all
  end
end

Create some settings,

Setting.create(var_name: 'domain', value: 'google.com')
Setting.create(var_name: 'subdomain', value: 'www')

You can then fetch a setting using Setting.fetch('domain').value #=> 'google.com'.

Settings.fetch('domain')    #=> Hits the database with Settings.all
Settings.fetch('subdomain') #=> Hits the results in @fetch_all
Settings.fetch('domain')    #=> Hits the results in @fetch_all

@fetch_all ||= all will call Setting.all the first time Setting.fetch_all is called and store the results in @fetch_all. Subsequent calls will use the results stored in @fetch_all.

Upvotes: 4

Related Questions