简体   繁体   English

如何在Ruby on Rails中获取翻译文件的反向查找含义

[英]How to get reverse lookup meaning on translation file in Ruby on Rails

I'm a user of RoR. 我是RoR的用户。

From the official documentation, I understand how to define translation file about activerecord. 从官方文档中,我了解如何定义有关activerecord的翻译文件。

Sample is about User mode. 示例与用户模式有关。

en:
  activerecord:
    models:
      user: Dude
    attributes:
      user:
        login: "Handle"

and get attribute meaning like this. 并获得这样的属性含义。 "login" -> "Handle" “登录” - >“处理”

User.human_attribute_name("login")

Now, I want to know the model attribute name. 现在,我想知道模型属性名称。 "Handle" -> "login" “处理” - >“登录”

How do I get this? 我怎么得到这个?

I did not see a method in I18n that has such functionality, but you can do some really nasty stuff if you want: 我没有在I18n中看到具有此类功能的方法,但如果您需要,可以做一些非常讨厌的事情:

kv = I18n::Backend::KeyValue.new({})
flat = kv.flatten_translations(:en, I18n.config.backend.send(:translations), false, nil)
flat.find {|key, value| value == "Handle"}

This should output en.activerecord.attributes.user.login 这应该输出en.activerecord.attributes.user.login

Elaborating on @phoet 's nice little hack (thanks!) 详细解释@phoet的漂亮小黑客(谢谢!)

module ReverseTranslationLookup
  extend self

  def lookup(locale, copy)
    locale_messages(locale)[copy]
  end

  private

  def locale_messages(locale)
    messages[locale] ||= build_backend(locale)
  end

  def messages
    @messages ||= {}
  end

  def build_backend(locale)
    backend      = I18n::Backend::KeyValue.new({})
    translations = I18n.config.backend.send(:translations)
    backend.flatten_translations(locale, translations, false, nil)
      .select { |key, val| val.is_a?(String) }
      .invert
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM