File tree Expand file tree Collapse file tree 3 files changed +65
-1
lines changed
Expand file tree Collapse file tree 3 files changed +65
-1
lines changed Original file line number Diff line number Diff line change @@ -213,6 +213,19 @@ cookies[:counter] = {
213213}
214214cookies[: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" , :permanent => true
228+ ```
216229
217230## Raising Errors
218231
Original file line number Diff line number Diff line change @@ -133,6 +133,26 @@ 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+ # @param options [Hash] The options used when redirect.
140+ # :permanent, default true.
141+ def redirect ( url , options = { } )
142+ merged_options = { :permanent => false } . merge ( options )
143+ if merged_options [ :permanent ]
144+ status 304
145+ else
146+ if env [ 'HTTP_VERSION' ] == 'HTTP/1.1' && request . request_method . to_s . upcase != "GET"
147+ status 303
148+ else
149+ status 302
150+ end
151+ end
152+ header "Location" , url
153+ body ""
154+ end
155+
136156 # Set or retrieve the HTTP status code.
137157 #
138158 # @param status [Integer] The HTTP Status Code to return for this request.
Original file line number Diff line number Diff line change @@ -204,6 +204,37 @@ 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+
228+ it "support permanent redirect" do
229+ subject . get ( '/hey' ) do
230+ redirect "/ha" , :permanent => 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
237+ end
207238
208239 it 'should not persist params between calls' do
209240 subject . post ( '/new' ) do
@@ -345,4 +376,4 @@ def memoized
345376 end
346377 end
347378 end
348- end
379+ end
You can’t perform that action at this time.
0 commit comments