Skip to content

Instantly share code, notes, and snippets.

View jarod022's full-sized avatar

Cyril Farré jarod022

View GitHub Profile
@jarod022
jarod022 / generic_cacher.rb
Created March 22, 2017 16:48
Rails: how to save up database queries using cache
class GenericCacher
attr_reader :cache_store
def initialize
@cache_store = ActiveSupport::Cache::FileStore.new(“#{Rails.root}# {location}”)
end
def write
cache_store.write(cache_key_env_based, subject)
end
@jarod022
jarod022 / settings_cacher.rb
Last active March 22, 2017 17:11
Rails: how to save up database queries using cache
class SettingsCacher < GenericCacher
private
def cache_key
'global_settings'
end
def subject
Setting.all.load
end
@jarod022
jarod022 / setting.rb
Created March 22, 2017 17:12
Rails: how to save up database queries using cache
class Setting < ActiveRecord::Base
after_save :update_cached_settings
private
def update_cached_settings
SettingsCacher.new.write
end
end
@jarod022
jarod022 / application_controller.rb
Created March 22, 2017 17:13
Rails: how to save up database queries using cache
class ApplicationController < ActionController::Base
before_action :fetch_settings
helper_method :settings
private
def fetch_settings
@__settings = SettingsCacher.new.fetch
end
protected