Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add redirect feature #166

Merged
merged 3 commits into from Apr 30, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.markdown
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
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
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