【问题标题】:How do I pass variables between routes without using sessions or haml in Sinatra?如何在不使用 Sinatra 中的会话或 haml 的情况下在路由之间传递变量?
【发布时间】:2014-11-27 16:37:26
【问题描述】:

例如:当你想将错误信息返回到另一个页面时

目前我正在这样做

  get '/' do
    erb :home
  end


  get '/send/:user' do
    Process.detach(fork{ exec "ruby send.rb #{params[:user]} > output.txt"})   
    session['msg'] = "Process for the user #{params[:user]} iniciated, it will take a few minutes"
    redirect '/'
  end

并在 .erb 中显示这样的消息

<span style="margin:auto; text-align: center; padding:10px"><%=session['msg']%></span>

它必须是使用会话变量的更好方法

使用:

  • ruby 2.1.2p95(2014-05-08 修订版 45877)[x86_64-darwin13.0]
  • 西纳特拉 (1.4.5)

【问题讨论】:

标签: ruby sinatra session-variables erb


【解决方案1】:

你真的应该使用Sinatra Flash 来实现你所追求的那种机制。 Flash 消息通常在一个请求后过期,因此您无需手动管理它们(它们确实使用后台会话进行存储):

require 'sinatra'
require 'sinatra/flash'

enable :sessions

get '/' do
   erb :home
end

get '/send/:user' do
    Process.detach(fork{ exec "ruby send.rb #{params[:user]} > output.txt"})   
    flash[:msg] = "Process for the user #{params[:user]} initiated, it will take a few minutes"
    redirect '/'
end

在 home.erb 中:

<span style="margin:auto; text-align: center; padding:10px"><%= flash[:msg] %></span>

【讨论】:

  • 比session好多了,至少不用每次都清空session变量,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-01
  • 2016-12-19
  • 2011-11-16
  • 2018-06-27
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
相关资源
最近更新 更多