Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing post data to other pages in Sinatra

Tags:

ruby

sinatra

This seems to work fine:

views/index.haml:

%form{:method => 'POST' :action => '/'}
  %label{:for => 'name'} Name:
    %input{:type => 'text, :value => @values[:name] || ""}
  %input{:type => 'submit'}

app.rb:

post '/' do
  @values = params
  haml :review
end

views/review.rb

Hello #{params[:name]}!

However, when I try to send my post-data to the same view on a different URL I get an error, or in other words:

app.rb:

post '/' do
  @values = params
  redirect '/review'
end

get '/review' do
  @values = params
  haml :review
end

The data is not going through, but no error is raised.

How do I send the post-data across pages like this? Ideally, I do not want to create a database.

like image 238
shicholas Avatar asked Sep 26 '12 03:09

shicholas


1 Answers

You can store the parameters in a session or specify the query string explicitly. Browser Redirect from Sinatra Documentation

As specified in the documentation, you may use sessions or convert the POST params to a query string and use it in the redirect method. A crude example would be:

Say the POST params hash inside the '/' block is:

{
  :name => "Whatever",
  :address => "Wherever"
}

This hash can be made into a string like so:

query = params.map{|key, value| "#{key}=#{value}"}.join("&")
# The "query" string now is: "name=Whatever&address=Wherever"

Now use this inside the post '/' do

redirect to("/review?#{query}")
like image 189
Kashyap Avatar answered Nov 09 '22 13:11

Kashyap