Skip to content

Commit 0fa3b9d

Browse files
committed
Support more kindly for after method
ref ruby-grape#1240
1 parent 76c900a commit 0fa3b9d

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

lib/grape/middleware/base.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def call!(env)
2727
ensure
2828
after_response = after
2929
end
30-
after_response || @app_response
30+
is_response_valid?(after_response) ? after_response : @app_response
3131
end
3232

3333
# @abstract
@@ -65,6 +65,17 @@ def mime_types
6565
end
6666
types_without_params
6767
end
68+
69+
def is_response_valid?(response)
70+
if response.is_a?(Array)
71+
status, headers, body = *response
72+
(status >= 100 && status < 600) && (headers.is_a?(Hash)) && body.respond_to?(:each)
73+
else
74+
response.is_a?(Rack::Response)
75+
end
76+
rescue
77+
false
78+
end
6879
end
6980
end
7081
end

spec/grape/middleware/base_spec.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,21 @@
4040

4141
context 'after callback' do
4242
before do
43-
allow(subject).to receive(:after).and_return([200, {}, 'Hello from after callback'])
43+
allow(subject).to receive(:after).and_return([200, {}, ['Hello from after callback']])
4444
end
4545

4646
it 'overwrites application response' do
47-
expect(subject.call!({}).last).to eq('Hello from after callback')
47+
expect(subject.call!({}).last).to eq(['Hello from after callback'])
48+
end
49+
end
50+
51+
context 'after callback with invalid response' do
52+
before do
53+
allow(subject).to receive(:after).and_return('invalid response')
54+
end
55+
56+
it 'does not overwrite application response' do
57+
expect(subject.call!({}).last).to eq('Hi there.')
4858
end
4959
end
5060

0 commit comments

Comments
 (0)