Skip to content

Commit 7e49d27

Browse files
committed
support permanent redirect, add document in readme
1 parent 1dfd1e6 commit 7e49d27

File tree

3 files changed

+33
-5
lines changed

3 files changed

+33
-5
lines changed

README.markdown

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,19 @@ cookies[:counter] = {
213213
}
214214
cookies[:counter][:value] +=1
215215
```
216+
## Redirect
217+
218+
You can redirect to a new url
219+
220+
``` ruby
221+
redirect "/new_url"
222+
```
223+
224+
use permanent redirect
225+
226+
``` ruby
227+
redirect "/new_url", true
228+
```
216229

217230
## Raising Errors
218231

lib/grape/endpoint.rb

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,16 @@ def error!(message, status=403)
136136
# Redirect to a new url.
137137
#
138138
# @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
139+
# @param permanent [Boolean] Whether use permanent redirect with status code 304.
140+
def redirect(url, permanent=false)
141+
if permanent
142+
status 304
143+
else
144+
if env['HTTP_VERSION'] == 'HTTP/1.1' && request.request_method.to_s.upcase != "GET"
145+
status 303
146+
else
147+
status 302
148+
end
144149
end
145150
header "Location", url
146151
body ""

spec/grape/endpoint_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,16 @@ def app; subject end
224224
last_response.status.should eq 303
225225
last_response.headers['Location'].should eq "/ha"
226226
end
227+
228+
it "support permanent redirect" do
229+
subject.get('/hey') do
230+
redirect "/ha", true
231+
end
232+
get '/hey'
233+
last_response.status.should eq 304
234+
last_response.headers['Location'].should eq "/ha"
235+
last_response.body.should eq ""
236+
end
227237
end
228238

229239
it 'should not persist params between calls' do

0 commit comments

Comments
 (0)