[英]ruby sinatra how to redirect with regex
I am trying to move stuff at root to /en/ directory to make my little service multi-lingual. 我正在尝试将根目录下的内容移动到/ en /目录,以使我的小服务使用多种语言。
So, I want to redirect this url 所以,我想重定向这个网址
mysite.com/?year=2018 mysite.com/?year=2018
to 至
mysite.com/en/?year=2018 mysite.com/en/?year=2018
My code is like 我的代码就像
get %r{^/(\\?year\\=\\d{4})$} do |c| redirect "/en/#{c}" end
but it seems like I never get #{c} part from the url. 但似乎我从未从网址中获得#{c}部分。
Why is that? 这是为什么? or are there just better ways to do this?
还是有更好的方法来做到这一点?
Thanks! 谢谢!
You can use the request.path
variable to get the information you're looking for. 您可以使用
request.path
变量来获取所需的信息。
For example, 例如,
get "/something" do
puts request.path # => "/something"
redirect "/en#{request.path}"
end
However if you are using query parameters (ie ?yeah=2000
) you'll have to manually pass those off to the redirect route. 但是,如果您使用查询参数(即
?yeah=2000
),则必须手动将这些参数传递给重定向路由。
Kind of non-intuitively, there's a helper method for this in ActiveRecord. 有点不直观,ActiveRecord中有一个辅助方法。
require 'active_record'
get "/something" do
puts params.to_param
# if params[:year] is 2000, you'll get "year=2000"
redirect "/en#{request.path}?#{params.to_param}"
end
You could alternatively write your own helper method pretty easily: 您也可以很容易地编写自己的帮助方法:
def hash_to_param_string(hash)
hash.reduce("") do |string, (key, val)|
string << "#{key}=#{val}&"
end
end
puts hash_to_param_string({key1: "val1", key2: "val2"})
# => "key1=val1&key2=val2"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.