助けてくれてありがとう。
私がしていること: 私は、複数の言語で利用できる必要がある企業の Web サイトを設計しています。
私がやったこと: いくつかの静的ページを持つレールアプリケーション。Rails で I18n 機能を使用する場合、特にルートを使用してロケールを設定する場合は、Ryan Bates の例を使用しました。
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}")
私の ApplicationController は次のようになります。
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
サーバー起動時のログには次のように表示されます。
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)
私がやろうとしていること:
ユーザーが URL でロケールを指定しない場合 (例: www.example.com のみを入力)、Rails は受け入れられたロケールを取得しrequest.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
、ビジターを好みの言語にリダイレクトします。この時点で、そもそも I18n.locale がどこに設定されているのかわかりません。