Skip to content

Commit

Permalink
Merge pull request #166 from allenwei/master
Browse files Browse the repository at this point in the history
Add redirect feature
  • Loading branch information
dblock committed Apr 30, 2012
2 parents bb4c77f + c7ad0a4 commit b13e123
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
13 changes: 13 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,19 @@ cookies[:counter] = {
}
cookies[:counter][:value] +=1
```
## Redirect

You can redirect to a new url

``` ruby
redirect "/new_url"
```

use permanent redirect

``` ruby
redirect "/new_url", :permanent => true
```

## Raising Errors

Expand Down
20 changes: 20 additions & 0 deletions lib/grape/endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,26 @@ def error!(message, status=403)
throw :error, :message => message, :status => status
end

# Redirect to a new url.
#
# @param url [String] The url to be redirect.
# @param options [Hash] The options used when redirect.
# :permanent, default true.
def redirect(url, options = {})
merged_options = {:permanent => false }.merge(options)
if merged_options[:permanent]
status 304
else
if env['HTTP_VERSION'] == 'HTTP/1.1' && request.request_method.to_s.upcase != "GET"
status 303
else
status 302
end
end
header "Location", url
body ""
end

# Set or retrieve the HTTP status code.
#
# @param status [Integer] The HTTP Status Code to return for this request.
Expand Down
33 changes: 32 additions & 1 deletion spec/grape/endpoint_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,37 @@ def app; subject end
last_response.body.should == '{"dude":"rad"}'
end
end

describe "#redirect" do
it "should redirect to a url with status 302" do
subject.get('/hey') do
redirect "/ha"
end
get '/hey'
last_response.status.should eq 302
last_response.headers['Location'].should eq "/ha"
last_response.body.should eq ""
end

it "should have status code 303 if it is not get request and it is http 1.1" do
subject.post('/hey') do
redirect "/ha"
end
post '/hey', {}, 'HTTP_VERSION' => 'HTTP/1.1'
last_response.status.should eq 303
last_response.headers['Location'].should eq "/ha"
end

it "support permanent redirect" do
subject.get('/hey') do
redirect "/ha", :permanent => true
end
get '/hey'
last_response.status.should eq 304
last_response.headers['Location'].should eq "/ha"
last_response.body.should eq ""
end
end

it 'should not persist params between calls' do
subject.post('/new') do
Expand Down Expand Up @@ -345,4 +376,4 @@ def memoized
end
end
end
end
end

0 comments on commit b13e123

Please sign in to comment.