Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

ruby - Passing variables between routes in Sinatra

I'm implementing sms-validation of registration on Sinatra site, and I got this code:

post '/reg' do
  phone = params[:phone].to_s
  code = Random.rand(1000..9999).to_s
  HTTParty.get('http://sms.ru/sms/send?api_id=' + api_id + phone + '&text=' + code)
end

This take users phone from post request, than generates 4 digit code, and sends code on number via get request to sms service. But, page doesn't reloading, because at that moment opens modal dialog, where user should type code. Button which opens modal simultaneously sends post via Ajax with this code:

$(document).ready(function(){
  $("#sendsms").click(function(){
    var phone = $("#phone").val();
    $.ajax({
      url: "/coop",
      data: {"phone": phone},
      type: "post"
    });
  });
});

It would be strange to check user's code on client side, thats why I got this action route:

post '/coop/checkcode' do
  usrcode = params[:code]
  if code == usrcode
    redirect '/reg/success'
  else
    redirect '/reg/fail'
  end
end

But I can't just take and type code var from first route in the checkcode route. But I need.

Is there exists any possible way to pass that variable or implement this somehow other way?

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should look into using sessions: here

first in config:

enable :sessions

now you get:

post '/reg' do
  phone = params[:phone].to_s
  session[:code] = Random.rand(1000..9999).to_s
  HTTParty.get('http://sms.ru/sms/send?api_id=' + api_id + phone + '&text=' + session[:code])
end

and

post '/coop/checkcode' do
  usrcode = params[:code]
  if session[:code] == usrcode
    redirect '/reg/success'
  else
    redirect '/reg/fail'
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...