今天来看看Rails对于不同locale的支持,我们使用Globalize插件
ruby script/plugin install \
http://svn.globalize-rails.org/svn/globalize/globalize/trunk
然后我们生成migration文件
ruby script/generate globalize
然后运行
rake db:migrate
然后我们需要在config/environment.rb里设置语言和默认locale
include Globalize
Locale.set_base_language 'en-US'
Locale.set 'en-US'
然后我们允许用户选择locale
class AccountsController < ApplicationController
def login
authentication....
session[:user] = user.id
session[:locale] = user.locale
redirect_to (go_url || home_url)
end
def logout
@session[:user] = nil
redirect_to home_url
end
def change_locale
session[:locale] = params[:locale] unless params[:locale].blank?
end
end
然后我们给ApplicationController添加一个before_filter
before_filter :set_locale
def set_locale
Locale.set session[:locale] unless session[:locale].blank?
true
end
我们来看看Globalize的一些helper方法,t()为translations,/()为printf-looking,如
<% unless params[:search].blank? %>
<p><%= "Found %d products." / @products.size %></p>
<% end %>
<%= link_to "Remove".t, :action => 'remove', :id => item.product_id %>
对于时间和货币使用loc()方法
<%= Time.now.loc "%H:%M %Z" %>
Globalize甚至可以翻译Model
class Product < ActiveRecord::Base
translates :name, :description
end
需要注意的是我们的Rails程序需要一致使用utf8编码
1,config/environment.rb
$KCODE ='u'
require 'jcode'
2,config/database.yml
对MySQL
encoding: utf8
对PostgreSQL
encoding: unicode
3,ApplicationController
after_filter :set_charset
def set_charset
unless @headers["Content-Type"] =~ /charset/i
@headers["Content-Type"] ||= ""
@headers["Content-Type"] += "; charset=utf-8"
end
end
更多细节参考
http://www.globalize-rails.org