跳至内容 跳至搜索

Active Model Translation

提供对象与 Rails 国际化 (i18n) 框架之间的集成。

最小化实现可以是

class TranslatedPerson
  extend ActiveModel::Translation
end

TranslatedPerson.human_attribute_name('my_attribute')
# => "My attribute"

这也提供了挂接到 Rails 国际化 API 所需的类方法,包括能够定义基于类的 i18n_scopelookup_ancestors 以在父类中查找翻译。

方法
H
I
L
包含的模块

实例公共方法

human_attribute_name(attribute, options = {})

将属性名称转换为更人性化的格式,例如“First name”而不是“first_name”。

Person.human_attribute_name("first_name") # => "First name"

使用 options 指定其他翻译选项。

# File activemodel/lib/active_model/translation.rb, line 46
def human_attribute_name(attribute, options = {})
  attribute = attribute.to_s

  if attribute.include?(".")
    namespace, _, attribute = attribute.rpartition(".")
    namespace.tr!(".", "/")

    defaults = lookup_ancestors.map do |klass|
      :"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
    end
    defaults << :"#{i18n_scope}.attributes.#{namespace}.#{attribute}"
  else
    defaults = lookup_ancestors.map do |klass|
      :"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}.#{attribute}"
    end
  end

  defaults << :"attributes.#{attribute}"
  defaults << options[:default] if options[:default]
  defaults << MISSING_TRANSLATION

  translation = I18n.translate(defaults.shift, count: 1, **options, default: defaults)
  translation = attribute.humanize if translation == MISSING_TRANSLATION
  translation
end

i18n_scope()

返回类的 i18n_scope。如果您想要自定义查找,请覆盖。

# File activemodel/lib/active_model/translation.rb, line 26
def i18n_scope
  :activemodel
end

lookup_ancestors()

在本地化字符串时,它将遍历此方法返回的查找,该方法用于 ActiveModel::Name#humanActiveModel::Errors#full_messagesActiveModel::Translation#human_attribute_name

# File activemodel/lib/active_model/translation.rb, line 34
def lookup_ancestors
  ancestors.select { |x| x.respond_to?(:model_name) }
end