Skip to content

Commit 1dfd1e6

Browse files
committed
Add redirect feature
1 parent 8ee8481 commit 1dfd1e6

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

lib/grape/endpoint.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,19 @@ def error!(message, status=403)
133133
throw :error, :message => message, :status => status
134134
end
135135

136+
# Redirect to a new url.
137+
#
138+
# @param url [String] The url to be redirect.
139+
def redirect(url)
140+
if env['HTTP_VERSION'] == 'HTTP/1.1' && request.request_method.to_s.upcase != "GET"
141+
status 303
142+
else
143+
status 302
144+
end
145+
header "Location", url
146+
body ""
147+
end
148+
136149
# Set or retrieve the HTTP status code.
137150
#
138151
# @param status [Integer] The HTTP Status Code to return for this request.

spec/grape/endpoint_spec.rb

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,27 @@ def app; subject end
204204
last_response.body.should == '{"dude":"rad"}'
205205
end
206206
end
207+
208+
describe "#redirect" do
209+
it "should redirect to a url with status 302" do
210+
subject.get('/hey') do
211+
redirect "/ha"
212+
end
213+
get '/hey'
214+
last_response.status.should eq 302
215+
last_response.headers['Location'].should eq "/ha"
216+
last_response.body.should eq ""
217+
end
218+
219+
it "should have status code 303 if it is not get request and it is http 1.1" do
220+
subject.post('/hey') do
221+
redirect "/ha"
222+
end
223+
post '/hey', {}, 'HTTP_VERSION' => 'HTTP/1.1'
224+
last_response.status.should eq 303
225+
last_response.headers['Location'].should eq "/ha"
226+
end
227+
end
207228

208229
it 'should not persist params between calls' do
209230
subject.post('/new') do
@@ -345,4 +366,4 @@ def memoized
345366
end
346367
end
347368
end
348-
end
369+
end

0 commit comments

Comments
 (0)