简体   繁体   中英

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.

So, I want to redirect this url

mysite.com/?year=2018

to

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.

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.

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.

Kind of non-intuitively, there's a helper method for this in 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM