【问题标题】:rails: how can I override a locale based on subdomain?rails:如何覆盖基于子域的语言环境?
【发布时间】:2013-02-22 09:47:50
【问题描述】:

我使用标准 Rails 机制对我的应用程序进行了国际化和本地化。 一切都存储在 en、fr、de.yml 文件中。

我的应用程序是多租户的,基于子域。

我希望允许我的用户覆盖应用程序中的某些翻译(例如,将“员工”更改为“关联”,因为它与他们自己的术语相匹配)。

我尝试根据每个请求更改 yml 文件的加载路径,但无济于事。

知道对于每个请求,我如何首先在我的用户特定的 yaml 文件中查找,如果翻译没有被覆盖,则回退到默认的 yaml 文件?

【问题讨论】:

  • I18n 允许连接任意后端,因此您可以构建自己的后端来处理应用程序的特殊逻辑

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


【解决方案1】:

假设您将子域存储在来自控制器过滤器的实例变量中,您可以覆盖翻译助手以首先使用特定于子域​​的范围进行查找,然后回退到指定或默认范围。像这样的:

module ApplicationHelper

  def t(key, original_options = {})
    options = original_options.dup
    site_translation_scope = ['subdomain_overrides', @subdomain.name]
    scope =
      case options[:scope]
      when nil
        site_translation_scope
      when Array
        options[:scope] = site_translation_scope + options[:scope]
      when String
        [site_translation_scope, options[:scope]].join(".")
      end
    translate(key, options.merge(:scope => scope, :raise => true))
  rescue I18n::MissingTranslationData
    translate(key, original_options)
  end

end

然后您添加您的子域特定覆盖,如下所示:

en:
  customer: Customer
  subdomain_overrides:
    subdomain_1:
      customer: Buyer

【讨论】:

    【解决方案2】:

    我最近创建了 I18n_global_scope gem,它完全符合您的描述,请查看源代码 https://github.com/mobilityhouse/i18n_global_scope 并让我知道您的反馈。

    【讨论】:

      【解决方案3】:

      如果您想允许租户使用特定语言但回退到默认语言,我已经写了一个微 library 来完成这项工作:

      https://github.com/ElMassimo/i18n_multitenant

      它负责将I18n 配置为回退到基本语言环境,允许您使用租户特定的翻译(如果可用)。它旨在与静态.yml 文件的默认后端一起使用,但它也应与其他I18n 后端一起使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-03
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多