在Rails 3

时间:2015-04-22 12:44:59

标签: ruby-on-rails ruby internationalization ruby-on-rails-3.2 rails-routing

使用Rails 3.2.8与gems下面的应用程序

gem 'friendly_id', '~> 4.0'
gem 'route_translator'

在/config/initializers/i18n.rb

TLD_LOCALES = {
  "com"  => :en,
  "jobs" => :en,
  "net"  => :en,
  "in"   => :en,
  "de"   => :de,
  "ch"   => :de,
  "at"   => :de,
  "br"   => :pt,
  "ar"   => :es,
  "cl"   => :es,
  "mx"   => :es 
}

在/app/controllers/application_controller.rb中,使用before-filter为每个请求设置语言环境:

before_filter :set_auto_locale
def set_auto_locale
  I18n.locale = TLD_LOCALES[request.host.split('.').last]
end

在routes.rb

localized do
  match "label_vacancies/:view_job"=>"job_seekers#view_job"
  get "label_aboutus", :to => "home#about_us", :as => "about_us"
end

当用户请求更改语言区域设置时,域下方应根据用户请求的区域设置加载。

在初始化程序中

domain_based_on_locale = {
    :en => "xxxxx.com",
    :de => "xxxxx.de",
    :es => "xxxxx.mx",
    :pt => "xxxxx.com.br"   
}

在/app/controllers/application_controller.rb

def set_manual_locale
  if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
    cookies['locale'] = { :value => params[:locale], :expires => 1.year.from_now }
    I18n.locale = params[:locale].to_sym
  elsif cookies['locale'] && I18n.available_locales.include?(cookies['locale'].to_sym)
    I18n.locale = cookies['locale'].to_sym
  end
  if domain_based_on_locale[I18n.locale] != request.host
    redirect_to "#{request.protocol}#{domain_based_on_locale[I18n.locale]}#{request.fullpath}", :status => :moved_permanently 
  else
    redirect_to root_path
  end
end

在这种情况下,用户更改以下网址中的语言会导致重定向问题,因为同一页面根据语言有不同的网址。

Aboutus:
http://xxxxxxx.com/about-us  # About us route in English
http://xxxxxxx.de/uber-uns      # About us route in German
http://xxxxxxx.mx/quienes-somos # About us route in Spanish

view Job:
http://xxxxxxx.com/jobs/rp-be-company-representante-de-ventas-22042015
http://xxxxxxx.de/ofertas-de-empleo/rp-be-company-representante-de-ventas-22042015

手动语言区域设置更改后,如何在新域中重定向到同一页面。是否可以将运行会话带到新域。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您需要翻译request.fullpath的每个细分(除了最后一个,看起来像资源slug)。您可以使用Rails的I18n手动执行此操作:

current_path = request.fullpath.split('/')
slug = current_path.pop
locale_path = current_path.map{|part| translate(part)}.join('/')
redirect_to "#{request.protocol}#{domain}#{locale_path}#{slug}"

或者,有一些宝石可以处理路线转换:

就会话而言,本地可能无法跨域共享Cookie。如果您创建了区域设置子域(例如de.xxxxx.com),则可以share the cookie across all of them。许多网站通过路径进行,例如。 xxxxx.com/de/,完全消除了这个问题。

支持完全不同的域需要您手动传输会话。你可以通过以下方式实现这一目标:

  • 生成随机转移令牌xxx123并将其附加到的会话保存在服务器端
  • 重定向到new.domain/path?token=xxx123
  • 使用令牌查找用户的会话并在浏览器中设置
  • 删除令牌以防止重播攻击

仔细考虑转移过程 - 当您执行此类操作时,很容易引入安全问题。 This SO thread使用从其他域加载的图像。