Skip to content

Commit

Permalink
Explicit cache key.
Browse files Browse the repository at this point in the history
This cache key defaults to `:rack`. Sub-classes need to explicitly change
this if they alter the way cached values are generated.
  • Loading branch information
ioquatix committed Mar 14, 2023
1 parent 4896eab commit c295b99
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
21 changes: 16 additions & 5 deletions lib/rack/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -501,11 +501,22 @@ def parseable_data?
raise
end

# This cache key is used by cached values generated by class_cache_for,
# specfically GET and POST. This is to ensure that the cache is not
# shared between instances of different classes which have different
# behaviour. This includes sub-classes that override query_parser or
# expand_params.
def cache_key
:rack
end

private def class_cache_for(key, validity_key, current_value)
cache_key = self.cache_key

if get_header(validity_key).equal?(current_value)
if cache = get_header(key)
if cache.key?(self.class)
value = cache[self.class]
if cache.key?(cache_key)
value = cache[cache_key]
if value.is_a?(Exception)
raise value.class, value.message, cause: value.cause
else
Expand All @@ -519,15 +530,15 @@ def parseable_data?
set_header(key, cache = {})
end

cache.fetch(self.class) do
cache.fetch(cache_key) do
value = yield(current_value)

# Only set this after generating the value, so that if an error or other cache depending on the same key, it will be invalidated correctly:
set_header(validity_key, current_value)

return cache[self.class] = value
return cache[cache_key] = value
rescue => error
cache[self.class] = error
cache[cache_key] = error
raise
end
end
Expand Down
2 changes: 1 addition & 1 deletion test/spec_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1564,7 +1564,7 @@ def initialize(*)
)

form_hash = {'foo' => 'bar'}.freeze
form_hash_cache[req.class] = form_hash
form_hash_cache[req.cache_key] = form_hash

req.POST.must_equal form_hash
end
Expand Down

0 comments on commit c295b99

Please sign in to comment.