I want to set the locale by the clients browserlocale request.env['HTTP_ACCEPT_LANGUAGE'] and by the url.
If the url has no params[:locale] it should use the browserlocale set the url.
Here is my code:
application_controller.rb
classApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
private
# set the languagedefset_localeif params[:locale].blank?
I18n.locale = extract_locale_from_accept_language_header
elseI18n.locale = params[:locale]
endend# pass in language as a default url parameterdefdefault_url_options(options = {})
{locale:I18n.locale}
end# extract the language from the clients browserdefextract_locale_from_accept_language_header
browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
ifI18n.available_locales.include? browser_locale
browser_locale
elseI18n.default_locale
endendend
routes.rb
Myapp::Application.routes.draw do# set language path
scope ":locale", locale:/#{I18n.available_locales.join("|")}/do
root :to => "mycontrollers#new"# set RESTful routes for the locations Controller
resources :mycontrollersend
match '*path', to: redirect("/#{I18n.locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }
match '', to: redirect("/#{I18n.locale}")
end
The Problem is that the routesfile gets executed first so the controller-actions won't grab anymore.
thanks a lot (+1)
That was the last piece of my puzzle!
Now everything is running properly!
I am so proud!
Thanks Ryan & Paul
I want to set the locale by the clients browserlocale
request.env['HTTP_ACCEPT_LANGUAGE']
and by the url.If the url has no
params[:locale]
it should use the browserlocale set the url.Here is my code:
The Problem is that the routesfile gets executed first so the controller-actions won't grab anymore.
Does anyone has a solution for that?