3

I was recently following Ryan Bate's Railscast on I18n adding multiple locations and setting the locale from the URL Params like

www.example.com/en/
www.example.com/fr/

Generally it works a treat, however I've noticed that if I manually try to remove the location from the url, the resulting redirect doesn't form correctly, seemingly encoding the / into %2F. For example if I remove the url from

www.example.com/fr/animals/horses
so it's www.example.com/animals/horses

then the redirect produces the following url:
www.example.com/fr/animals%2Fhorses

here's part of my routes.rb

scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
 resources animals
end

match '*path', to: redirect("/#{I18n.default_locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }
match '', to: redirect("/#{I18n.default_locale}")

I was trying to figure out a way of fitting CGI::escape into the {path} but nothing I've tried so far has worked. Does anyone know the correct code to fix this problem?

Rails 3.2.6 / Ruby 1.9.2

Thanks

Gareth Jones
  • 1,760
  • 1
  • 14
  • 24

1 Answers1

9

i guess what you need to do is using a block:

match '*path', to: redirect {|params| "/bla/#{CGI::unescape(params[:path])}" }

have a look at the guides for more info http://guides.rubyonrails.org/routing.html#redirection

phoet
  • 18,688
  • 4
  • 46
  • 74
  • 4
    Perfect, thanks a lot! For others interested I used the following: `match '*path', to: redirect {|params| "/#{I18n.default_locale}/#{CGI::unescape(params[:path])}" }, constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }` – Gareth Jones Jul 10 '12 at 18:38
  • @GarethJones and @phoet , thankyou so much , i was struggling with `%2 ` – Paritosh Piplewar Nov 29 '12 at 13:58
  • `match '*path', to: redirect {|params| "/#{I18n.default_locale}/#{params[:path]}" }` worked for me without the CGI::unescape – ryan2johnson9 Apr 08 '15 at 10:04
  • What about the query params in the original request? For me the query params get stripped off after redirection. – Anshul Mengi Jun 25 '15 at 03:25
  • well, have you looked into what else the params hash includes? – phoet Jun 25 '15 at 20:19