4

Thanks everyone for your help.

WHAT I AM DOING: I'm designing a corporate website which must be available in multiple languages

WHAT I HAVE DONE: A rails application with several static pages. I used Ryan Bates example on using I18n features in rails, in particular using routes to set the locale:

MyApp::Application.routes.draw do

  scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
    root to: 'static_pages#home'

    match '/about', to: 'static_pages#about'
    match '/contact', to: 'static_pages#contact'
  end

  match '*path', to: redirect("/#{I18n.locale}/%{path}")  
  match '', to: redirect("/#{I18n.locale}")

My ApplicationController looks as follows:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale

  private
    def set_locale      
        I18n.locale = params[:locale] || I18n.default_locale
    end    

    def default_url_options(options = {})
        {locale: I18n.locale}
    end       
end

My log at server start displays the following:

Started GET "/en" for 127.0.0.1 at 2012-11-14 22:41:01 +0400
Processing by StaticPagesController#home as HTML
  Parameters: {"locale"=>"en"}
  Rendered static_pages/home.en.html.erb within layouts/application (1.0ms)
Compiled custom.css  (5905ms)  (pid 9864)
Compiled application.css  (15ms)  (pid 9864)
  Rendered layouts/_shim.html.erb (0.0ms)
  Rendered layouts/_header.html.erb (12.0ms)
  Rendered layouts/_footer.html.erb (2.0ms)
Completed 200 OK in 6741ms (Views: 6740.4ms | ActiveRecord: 0.0ms)

WHAT I AM TRYING TO DO: I would like that when a user does not specify the locale in the url (e.g. types only www.example.com), rails get the accepted locales from request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first and redirects the visitor to his preferred language. At this point I can't figure out where my I18n.locale is set in the first place.

magom001
  • 608
  • 6
  • 16
  • Has there been any answer to this issue. I am half way there - however, the locale gets set before I get to set_locale which is in my applicaiton controller .... – Georg Keferböck Apr 19 '14 at 01:14

2 Answers2

1

This works magic HTTP_ACCEPT_LANGUAGE

Another to consider Locale Setter

The latter one allows you to check for user preference, http_accept_lang code, etc.

Georg Keferböck
  • 1,967
  • 26
  • 43
0

I am working on exactly the same case as yours! perhaps you should try this

Also refer to my question where there are useful answers.

Once I get this working I will post an answer

Community
  • 1
  • 1
RajG
  • 832
  • 2
  • 15
  • 26