Skip to content

Instantly share code, notes, and snippets.

@cpuguy83
Last active December 10, 2015 23:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpuguy83/4512161 to your computer and use it in GitHub Desktop.
Save cpuguy83/4512161 to your computer and use it in GitHub Desktop.
I noticed in my models I had several methods that could use some caching to speed things up a bit, especially because lots of joins were involved to make it happen. I got tired of calling "Rails.cache.fetch __method__, self" over and over and over. Taking a cue from the ActionView::Helpers::CacheHelper 'cache' call and the whole Russian-doll cac…
module CacheHelper
extend ActiveSupport::Concern
included do
extend Cacher
include Cacher
cattr_accessor :updated_column_name
self.updated_column_name ||= :change_time
cattr_accessor :file_location
cattr_accessor :file_digest
self.file_location ||= "#{Rails.root}/app/models/#{self.to_s.split('::').join('/').underscore.downcase}.rb" if defined? Rails
self.file_digest ||= Digest::MD5.hexdigest(File.read(self.file_location)) if self.file_location
end
module Cacher
def cache(key='', options={}, &block)
unless options[:overwrite_key]
calling_method = caller[0][/`([^']*)'/, 1]
key << calling_method << '/'
key << self.cache_key << '/'
key << self.file_digest
end
puts key if options[:debug]
filtered_options = options.except(:overwrite_key, :debug)
Rails.cache.fetch key, filtered_options do
block.call
end
end
end
module ClassMethods
# Create cache_key for class, use most recently updated record
unless self.respond_to? :cache_key
define_method :cache_key do
key = order("#{self.updated_column_name} DESC").first.cache_key if self.superclass.to_s == "ActiveRecord::Base"
key << "/#{self.to_s}"
end
end
end
end
class MyClass < ActiveRecord::Base
include CacheHelper
def some_cachable_method
cache do
# stuff
end
end
def some_cachable_method_with_custom_cache_key
cache ['some special key'] do
# stuff
end
end
def method_with_cach_options
cache 'my key', expires_in: 30.minutes do
# stuff
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment