From 1517aac3e90b660dfc1913b1006d5960fbf2f0fa Mon Sep 17 00:00:00 2001 From: Hermann Mayer Date: Mon, 4 Oct 2021 15:42:12 +0200 Subject: [PATCH] Memoize the result of Grape::Middleware::Base#response. Signed-off-by: Hermann Mayer --- CHANGELOG.md | 1 + lib/grape/middleware/base.rb | 2 +- spec/grape/middleware/base_spec.rb | 16 ++++++++++------ 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2177cee7f..9c5cd79ecc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ #### Fixes +* [#2192](https://github.com/ruby-grape/grape/pull/2192): Memoize the result of Grape::Middleware::Base#response - [@Jack12816](https://github.com/Jack12816). * Your contribution here. ### 1.6.0 (2021/10/04) diff --git a/lib/grape/middleware/base.rb b/lib/grape/middleware/base.rb index 132353a675..5eb998fc08 100644 --- a/lib/grape/middleware/base.rb +++ b/lib/grape/middleware/base.rb @@ -60,7 +60,7 @@ def after; end def response return @app_response if @app_response.is_a?(Rack::Response) - Rack::Response.new(@app_response[2], @app_response[0], @app_response[1]) + @app_response = Rack::Response.new(@app_response[2], @app_response[0], @app_response[1]) end def content_type_for(format) diff --git a/spec/grape/middleware/base_spec.rb b/spec/grape/middleware/base_spec.rb index 02a745e114..57cba82d1a 100644 --- a/spec/grape/middleware/base_spec.rb +++ b/spec/grape/middleware/base_spec.rb @@ -77,42 +77,46 @@ describe '#response' do subject { Grape::Middleware::Base.new(response) } + before { subject.call({}) } + context Array do let(:response) { ->(_) { [204, { abc: 1 }, 'test'] } } it 'status' do - subject.call({}) expect(subject.response.status).to eq(204) end it 'body' do - subject.call({}) expect(subject.response.body).to eq(['test']) end it 'header' do - subject.call({}) expect(subject.response.header).to have_key(:abc) end + + it 'returns the memoized Rack::Response instance' do + expect(subject.response).to be(subject.response) + end end context Rack::Response do let(:response) { ->(_) { Rack::Response.new('test', 204, abc: 1) } } it 'status' do - subject.call({}) expect(subject.response.status).to eq(204) end it 'body' do - subject.call({}) expect(subject.response.body).to eq(['test']) end it 'header' do - subject.call({}) expect(subject.response.header).to have_key(:abc) end + + it 'returns the memoized Rack::Response instance' do + expect(subject.response).to be(subject.response) + end end end