Sinatra中的会话:用于传递变量



所以我有一段代码,看起来像:

post '/calendar' do
  #pull variables from form
  @cal = a.makeCal(form, variables) #do some work here with variables
  session["value"] == @cal
  haml :calendar
end

然后是这个

get '/print' do
   @cal = session["value"]
   haml :print
end

我所做的测试是通过将表单发布到/calendar创建一个日历。接下来我手动进入/print,我希望变量@cal在cookie中持久化。我应该这么做吗?我这样做对吗?

我要做的是取@cal值,这是四个数组彼此内部,并将其传递到打印页面,而无需重新计算@cal。尝试通过会话来做到这一点是正确的方法吗?

您的post路由中有一个错字:

session["value"] == @cal
#                ^^ compares for equality, does not set.

这不会影响会话,但只会计算为true或(更有可能)false

@cal是什么类型的对象,您使用什么作为会话支持?(这些cookie支持的会话,即Rack::Session::Cookie,是通过enable :sessions启用的吗?如果是,你的对象是否一定能够通过Marshal序列化?)

编辑

是的,如果你改正了那个错字,你的东西应该可以用了。

这是一个为我工作的测试应用程序…

require 'sinatra'
enable :sessions
get('/'){ haml :show_and_go }
post '/' do
  session["foo"] = [[[1,2],[3,4]],[5,6]]
  "Now get it!n"
end
__END__
@@show_and_go
%p= session["foo"].inspect
%form(method='post' action='/')
  %button go

…这是对它的实际测试。我们看到,没有cookie就没有会话,但是一旦写入cookie,下一个请求就会使其工作。这在浏览器中也同样有效:

phrogz$ cat cookies.txt
cat: cookies.txt: No such file or directory
phrogz$ curl http://localhost:4567/                      # GET
<p>nil</p>
<form action='/' method='post'>
  <button>go</button>
</form>
phrogz$ curl -d "" -c cookies.txt http://localhost:4567  # POST
Now get it!
phrogz$ curl -b cookies.txt http://localhost:4567        # GET, with cookies
<p>[[[1, 2], [3, 4]], [5, 6]]</p>
<form action='/' method='post'>
  <button>go</button>
</form>

最新更新