Gus Powell
Gus Powell

Reputation: 53

Using variables across 'get' and 'post' routes in Sinatra

I'm using Sinatra and I'm receiving params of a restaurant order (item, quantity, table_number) with an html/erb form in a post request. This is all working splendidly....

get '/mainpage' do
  @time = Time.new.strftime("%B %e, %Y")
  erb :mainpage
end

post '/mainpage' do
  table_number = params[:table_number].to_i
  item = params[:item]
  quantity = params[:quantity].to_i
  @order = "#{table_number}...#{item}... #{quantity}"
  redirect to('/mainpage')
end

The problem comes when I wish to make the @order variable available in the 'mainpage' get request, so my html/erb page can use it like so:

<section class ="table-order">
  <%= @order %>
</section>

How would I go about doing this?

Upvotes: 0

Views: 1822

Answers (1)

theunraveler
theunraveler

Reputation: 3284

If your @order is really only a string and not some more complex object, you can use URL parameters to do this. For example:

get '/mainpage' do
  @time = Time.new.strftime("%B %e, %Y")
  @order = params[:order] if params[:order]
  erb :mainpage
end

post '/mainpage' do
  table_number = params[:table_number].to_i
  item = params[:item]
  quantity = params[:quantity].to_i
  order = "#{table_number}...#{item}... #{quantity}"
  redirect to("/mainpage?order=#{order}")
end

If your @order is some more complex object or you need it to persist for more than one redirect, consider using the session to store it instead. Something like this:

get '/mainpage' do
  @time = Time.new.strftime("%B %e, %Y")
  @order = session[:order] if session[:order]
  erb :mainpage
end

post '/mainpage' do
  table_number = params[:table_number].to_i
  item = params[:item]
  quantity = params[:quantity].to_i
  session[:order] = "#{table_number}...#{item}... #{quantity}"
  redirect to('/mainpage')
end

See Sinatra's docs for more information on generating URLs and using session.

Upvotes: 1

Related Questions