Last active
December 10, 2015 23:48
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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