2010年5月14日金曜日

Rails(3beta3) で国際化(I18n) その1

Rails3 で国際化を試していく。
自分の中でもあやふやだった部分を潰していく。(ブラウザの言語設定は本当に参照できないのかとか)

テスト用の MVC を生成して確認していく。
$ rails g scaffold state code:string, name:string


ブラウザの言語設定で判定する場合
HTTP_ACCEPT_LANGUAGE を参照する。

# app/controllers/application_controller.rb
before_filter :set_locale
def set_locale
I18n.locale = request.env['HTTP_ACCEPT_LANGUAGE'].split(",").first
end

URL で判定する場合

# app/controllers/application_controller.rb
before_filter :set_locale
def set_locale
I18n.locale = params[:locale]
end


# config/routes.rb
scope "/:locale" do
map.resources :states
end

$ rake routes
GET /:locale/states(.:format) {:action=>"index", :controller=>"states"}
states POST /:locale/states(.:format) {:action=>"create", :controller=>"states"}
new_state GET /:locale/states/new(.:format) {:action=>"new", :controller=>"states"}
GET /:locale/states/:id(.:format) {:action=>"show", :controller=>"states"}
PUT /:locale/states/:id(.:format) {:action=>"update", :controller=>"states"}
state DELETE /:locale/states/:id(.:format) {:action=>"destroy", :controller=>"states"}
edit_state GET /:locale/states/:id/edit(.:format) {:action=>"edit", :controller=>"states"}

URL パラメータで判定する場合
ロケールの選択は上記URL で判定する場合と同様で before_filter で行う。
rails で生成する URL には自動で現在設定されているロケールを付け足す。

# app/controllers/application_controller.rb
def default_url_options(options={})
{ :locale => I18n.locale }
end

routes は普通の設定で問題ない。(ってかこっちじゃないと動かない)

# config/routes.rb
map.resources :states

ドメインから判定する方法もあるらしいが、com などだったらどうするんだろう?
と、いうことでドメインはぱす。
RESTful で考えると URL か URL Param になる。
が、やっぱりブラウザの言語設定で判断したいかな。

参考
http://guides.rubyonrails.org/i18n.html

0 件のコメント: