Skip to content

Commit

Permalink
Improve caching (#861)
Browse files Browse the repository at this point in the history
Co-authored-by: Will Cosgrove <[email protected]>
  • Loading branch information
joeldrapper and willcosgrove authored Feb 14, 2025
1 parent 5bb664a commit 8db1b4f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
2 changes: 1 addition & 1 deletion lib/phlex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion lib/phlex/fifo_cache_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
24 changes: 17 additions & 7 deletions lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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?
Expand Down

0 comments on commit 8db1b4f

Please sign in to comment.