在Rails中仅在运行时设置一次语言环境

时间:2013-10-03 13:24:26

标签: ruby-on-rails ruby-on-rails-3 internationalization ruby-on-rails-4 rails-i18n

有没有办法设置语言环境并在请求之间设置它而不使用应用程序控制器中的before_action / before_filter?

我正试图避免目前的解决方案:

class ApplicationController < ActionController::Base
  before_action :set_locale

  def set_locale
    I18n.locale = current_user.locale if current_user
  end  
end

class LocaleController < ApplicationController
  skip_authorization_check

  def index
    locale = params[:locale]
    raise 'Unsupported locale' unless ['en', 'pt'].include?(locale)
    error_message = "Could not set locale" unless current_user.update_column(:locale, locale)
    I18n.locale = current_user.locale if error_message.nil?
    redirect_to :back, :alert => error_message
  end
end

1 个答案:

答案 0 :(得分:1)

您应该只使用

class ApplicationController < ActionController::Base

  catrr_accesor :locale_set
  before_action :set_locale :if => lambda {|c| locale_set}


  def set_locale
    I18n.locale = current_user.locale if current_user
    ApplicationController.locale_set = true
  end  
end

从代码中可以看出,其他控制器继承了这一点。

也许你想做类似的事情:

  def set_locale
    I18n.locale = user_signed_in? ? current_user.locale.to_sym : (params[:local] || I18n.default_locale)
  end

为了摆脱设计,你可以用这样的东西结束:

  # get locale of user
  def after_sign_in_path_for(resource_or_scope)
    if resource_or_scope.is_a?(User) && resource_or_scope.locale !=  I18n.locale
      I18n.locale = resource_or_scope.locale.to_sym || I18n.default_locale
    end
    session[:previous_url] || root_path
  end