【问题标题】:Setting the locale at runtime just once in Rails在 Rails 中只在运行时设置一次语言环境
【发布时间】:2013-10-03 13:24:25
【问题描述】:

有没有办法设置区域设置并在请求之间保持设置而不在应用程序控制器中使用 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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 我试图避免使用 before_filter/before_action 方法。
    • 也许可以在过滤器之前尝试这个,我希望它应该只运行一次。如果仍然不是你想要的,如果你使用一些钩子来设计怎么样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 2012-10-22
    相关资源
    最近更新 更多