From 8db1b4f62378f0dbc0bfbb6682cf80ae63c1eb81 Mon Sep 17 00:00:00 2001 From: Joel Drapper Date: Fri, 14 Feb 2025 16:15:16 +0000 Subject: [PATCH] Improve caching (#861) Co-authored-by: Will Cosgrove --- lib/phlex.rb | 2 +- lib/phlex/fifo_cache_store.rb | 4 +++- lib/phlex/sgml.rb | 24 +++++++++++++++++------- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/lib/phlex.rb b/lib/phlex.rb index 5518f480..f0868f79 100644 --- a/lib/phlex.rb +++ b/lib/phlex.rb @@ -23,7 +23,7 @@ module Phlex Escape = ERB::Escape - DEPLOY_KEY = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) + DEPLOYED_AT = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) CACHED_FILES = Set.new ATTRIBUTE_CACHE = FIFO.new diff --git a/lib/phlex/fifo_cache_store.rb b/lib/phlex/fifo_cache_store.rb index 5fda050d..e7cdc075 100644 --- a/lib/phlex/fifo_cache_store.rb +++ b/lib/phlex/fifo_cache_store.rb @@ -39,7 +39,9 @@ def map_key(value) when String, Symbol, Integer, Float, Time, true, false, nil value else - if value.respond_to?(:cache_key) + if value.respond_to?(:cache_key_with_version) + map_key(value.cache_key_with_version) + elsif value.respond_to?(:cache_key) map_key(value.cache_key) else raise ArgumentError.new("Invalid cache key: #{value.class}") diff --git a/lib/phlex/sgml.rb b/lib/phlex/sgml.rb index fa640958..6409bdc6 100644 --- a/lib/phlex/sgml.rb +++ b/lib/phlex/sgml.rb @@ -233,11 +233,12 @@ def cache(*cache_key, **, &content) location = caller_locations(1, 1)[0] full_key = [ - Phlex::DEPLOY_KEY, # invalidates the key when deploying new code in case of changes - self.class.name, # prevents collisions between classes - location.base_label, # prevents collisions between different methods - location.lineno, # prevents collisions between different lines - cache_key, # allows for custom cache keys + app_version_key, # invalidates the key when deploying new code in case of changes + self.class.name, # prevents collisions between classes + (self.class.object_id if enable_cache_reloading?), # enables reloading + location.base_label, # prevents collisions between different methods + location.lineno, # prevents collisions between different lines + cache_key, # allows for custom cache keys ].freeze low_level_cache(full_key, **, &content) @@ -276,12 +277,21 @@ def low_level_cache(cache_key, **options, &content) end end + private + + # Override this method to use a different deployment key. + def app_version_key + Phlex::DEPLOYED_AT + end + # Override this method to use a different cache store. def cache_store - raise "Cache store not implemented" + raise "Cache store not implemented." end - private + def enable_cache_reloading? + false + end def vanish(*args) return unless block_given?