如何在Sinatra中的处理程序(路由)之间传递变量(没有Flash,Sessions,@@class_variable



假设你有:


get '/' do
  haml :index
end

get '/form' do haml :form end

post '/form' do @message = params[:message] redirect to ('/') --- how to pass @message here? end

I'd like the @message instance variable to be available (passed to) in "/" action as well, so I can show it in haml view. How can I do that without using session, flash, a @@class_variable, or db persistence ?

I'd simply like to pass values as if I was working with passing values between methods.

I don't want to use session cookies because user could have them turned off, I don't like it being a class variable which is exposed to all code, and I don't need to overhead of a db.

Thanks

edit:

This is another question explaining a very easy way to deal with this in rails

Passing parameters in rails redirect_to

Following is more info on the topic i gathered from forums, which works in rails but, to my experience, not in Sinatra (but please check it out because I might have done something wrong):

If you are redirecting to action2 at the end of action1, just append the value to the end of the redirect:

my_var = <some logic>
redirect_to :action => 'action2', :my_var => my_var

在同一线程上,另一个用户建议:

def action1
  redirect_to :action => 'action2', :value => params[:current_varaible]
end
def action2
 puts params[:value].inspect
end

来源: http://www.ruby-forum.com/topic/134953

这样的事情可以在辛纳屈工作吗?谢谢

尝试

before do
  @message = params[:message]
end

并且@message应该在任何路线中可用

编辑

post '/form' do
  @message = params[:message]
  #redirect to ('/') --- how to pass @message here?
  haml :index, locals: {msg: @message}
end

不要使用redirect然后你可以传递locals哈希。在你的 index.haml 中msg变量应该可用。

我能想到的唯一方法是将东西塞进̀Thread.current[:variableName]。 我不声称这是最好或安全的解决方案。 特别是,一旦完成该哈希条目,应将其删除/设置为nil。

最新更新