Skip to content

Commit

Permalink
Fixes to cache_for - all tests passing.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Mar 14, 2023
1 parent 6b0d994 commit 888ac32
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
13 changes: 8 additions & 5 deletions lib/rack/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,8 @@ def parseable_data?
PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
end

private def cache_for(key, validity_key, current_input)
if get_header(validity_key).equal?(current_input)
private def cache_for(key, validity_key, current_value)
if get_header(validity_key).equal?(current_value)
if cache = get_header(key)
if cache.key?(self.class)
value = cache[self.class]
Expand All @@ -492,16 +492,19 @@ def parseable_data?
end
end
end
else
set_header(validity_key, current_input)
end

unless cache
set_header(key, cache = {})
end

cache.fetch(self.class) do
return cache[self.class] = yield(current_input)
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
rescue => error
cache[self.class] = error
raise
Expand Down
17 changes: 12 additions & 5 deletions test/spec_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1554,12 +1554,19 @@ def initialize(*)
rack_input.write(input)
rack_input.rewind

req = make_request Rack::MockRequest.env_for("/",
"rack.request.form_hash" => { 'foo' => 'bar' },
"rack.request.form_input" => rack_input,
:input => rack_input)
form_hash_cache = {}

req = make_request Rack::MockRequest.env_for(
"/",
"rack.request.form_hash" => form_hash_cache,
"rack.request.form_input" => rack_input,
:input => rack_input
)

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

req.POST.must_equal req.env['rack.request.form_hash']
req.POST.must_equal form_hash
end

it "conform to the Rack spec" do
Expand Down

0 comments on commit 888ac32

Please sign in to comment.