Sign in through GitHub

Please read for an updated status on RailsCasts:

Learn more or hide this

HaNdTriX's Profile

GitHub User: HaNdTriX

Comments by

Avatar

thanks a lot (+1)

That was the last piece of my puzzle!
Now everything is running properly!

I am so proud!
Thanks Ryan & Paul

Avatar

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
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale
  
private
  
  # set the language
  def set_locale
    if params[:locale].blank?
      I18n.locale = extract_locale_from_accept_language_header
    else
      I18n.locale = params[:locale]
    end
  end
  
  # pass in language as a default url parameter
  def default_url_options(options = {})
    {locale: I18n.locale}
  end
  
  # extract the language from the clients browser
  def extract_locale_from_accept_language_header
    browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first 
    if I18n.available_locales.include? browser_locale
      browser_locale
    else
      I18n.default_locale
    end
  end
end
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 :mycontrollers

  end

  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.

Does anyone has a solution for that?