32

What's Sinatra's equivalent of Rails' redirect_to method? I need to follow a Post/Redirect/Get flow for a form submission whilst preserving the instance variables that are passed to my view. The instance variables are lost when using the redirect method.

John Topley
  • 113,588
  • 46
  • 195
  • 237
  • http://stackoverflow.com/questions/4726884/can-you-specify-the-http-method-to-use-with-sinatras-redirect – Dmitry Feb 28 '13 at 17:09
  • You may want to take a look at Net::HTTP http://stackoverflow.com/questions/10184737/how-can-i-make-a-post-request-inside-ruby-sinatra – Gus Shortz Jun 15 '13 at 11:47

2 Answers2

60

Redirect in Sinatra is the most simple to use.

So the code below can explain:

require 'rubygems'
require 'sinatra'

get '/' do
  redirect "http://example.com"
end

You can also redirect to another path in your current application like this, though this sample will delete a method.

delete '/delete_post' do
  redirect '/list_posts'
end

A very common place where this redirect instruction is used is under Authentication

def authorize!
  redirect '/login' unless authorized?
end

You can see more samples under:

Sinatra Manual

FAQ

Extensions

As for your second question, passing variables into views, it's possible like this:

get '/pizza/:id' do
  # makeing lots of pizza
  @foo = Foo.find(params[:id])
  erb '%h1= @foo.name'
end
Rapptz
  • 20,807
  • 5
  • 72
  • 86
include
  • 2,108
  • 16
  • 13
6

The Sinatra Book should clear your question. Especially the "Redirect" part.

Quoted from the book:

The redirect actually sends back a Location header to the browser, and the browser makes a followup request to the location indicated. Since the browser makes that followup request, you can redirect to any page, in your application, or another site entirely.

The flow of requests during a redirect is: Browser –> Server (redirect to ’/’) –> Browser (request ’/’) –> Server (result for ’/’)

Community
  • 1
  • 1
scable
  • 4,064
  • 1
  • 27
  • 41
  • 1
    The solution is to store things in the session. All the values you need after the redirect that are currently in ivars should be put in the session instead. – Sami Samhuri Dec 01 '11 at 19:05
  • I recently asked a similar question, but have not yet found a definitive answer in case cookies are disabled on the client side... Is what you suggest the only solution you know of ? Anyone else ? Thanks – Redoman Oct 20 '12 at 04:05
  • 2
    The sinatra book link is no longer available. – Andres Dec 08 '14 at 23:04
  • Seems they have some hosting issues: https://github.com/sinatra/sinatra-book/issues/71 – scable Dec 09 '14 at 08:51