Skip to content

Instantly share code, notes, and snippets.

@sirwolfgang
Last active July 5, 2016 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirwolfgang/4fe62e05054002ec40b2 to your computer and use it in GitHub Desktop.
Save sirwolfgang/4fe62e05054002ec40b2 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
module ClassCacheKey
extend ActiveSupport::Concern
module ClassMethods
def cache_key(scope = all)
timestamp = DateTime.new(scope.maximum(:updated_at).to_i).utc.to_s(:number)
scope_sql = Digest::SHA1.hexdigest(scope.to_sql)
"#{model_name.cache_key}::#{scope_sql}\##{scope.count}-#{timestamp}"
end
end
end
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ClassCacheKey, type: :concern do
let(:active_record_klass) { CHANGE_ME }
let!(:instance_one) { create(active_record_klass.name.downcase.to_sym) }
let!(:instance_two) { create(active_record_klass.name.downcase.to_sym) }
it 'makes a key different per sql statement' do
expect(active_record_klass.cache_key).not_to eq active_record_klass.order(:created_at).cache_key
end
it 'generates a different key after record update' do
active_record_klass.uncached do
expect do
sleep 1
instance_one.touch
end.to change(active_record_klass, :cache_key)
end
end
it 'generates a different key after record addition' do
expect do
create(active_record_klass.name.downcase.to_sym)
end.to change(active_record_klass, :cache_key)
end
it 'generates a different key after record deletion' do
expect do
instance_one.destroy
end.to change(active_record_klass, :cache_key)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment