10

I'm trying to pass data between blocks using sinatra. For example:

@data = Hash.new
post "/" do
   @data[:test] = params.fetch("test").to_s
   redirect "/tmp"
end

get "/tmp" do
   puts @data[:test]
end

However whenever i get to the tmp block @data is nil and throws an error. Why is that?

Dan Galipo
  • 268
  • 3
  • 8

1 Answers1

16

The reason is because the browser actually performs two separate HTTP requests.

Request: POST /
Response: 301 -> Location: /tmp
Request: GET /tmp
Response: ...

Two requests means two separate processes thus the @data instance variable is cleared once the first response is sent. If you want to preserve the information, you need to use cookies or sessions, otherwise pass the data in querystring

post "/" do
   test = params[:test]
   redirect "/tmp?test=#{test}"
end

get "/tmp" do
   puts params[:test]
end
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • One common need is to be able to display errors/notices when redirecting. It looks like some people use the [sinatra-flash gem](https://github.com/SFEley/sinatra-flash) for that, which uses a session-based strategy. See http://stackoverflow.com/a/7178664/1154642 – bryanbraun Jan 05 '14 at 21:26