Active Model 国际化¶ ↑
提供您的对象与 Rails 国际化 (i18n) 框架之间的集成。
一个最小化的实现可以是
class TranslatedPerson extend ActiveModel::Translation end TranslatedPerson.human_attribute_name('my_attribute') # => "My attribute"
这还提供了连接到 Rails 国际化 API 所需的类方法,包括能够定义一个基于类的 i18n_scope 和 lookup_ancestors 来在父类中查找翻译。
方法
包含的模块
Attributes
| [RW] | raise_on_missing_translations |
实例公共方法
human_attribute_name(attribute, options = {}) 链接
将属性名称转换为更人性化的格式,例如“First name”(名字)而不是“first_name”。
Person.human_attribute_name("first_name") # => "First name"
使用 options 指定额外的翻译选项。
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/translation.rb, line 48 def human_attribute_name(attribute, options = {}) attribute = attribute.to_s if attribute.include?(".") namespace, _, attribute = attribute.rpartition(".") namespace.tr!(".", "/") if attribute.present? key = "#{namespace}.#{attribute}" separator = "/" else key = namespace separator = "." end defaults = lookup_ancestors.map do |klass| :"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}#{separator}#{key}" end defaults << :"#{i18n_scope}.attributes.#{key}" defaults << :"attributes.#{key}" else defaults = lookup_ancestors.map do |klass| :"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}.#{attribute}" end end raise_on_missing = options.fetch(:raise, Translation.raise_on_missing_translations) defaults << :"attributes.#{attribute}" defaults << options[:default] if options[:default] defaults << MISSING_TRANSLATION unless raise_on_missing translation = I18n.translate(defaults.shift, count: 1, raise: raise_on_missing, **options, default: defaults) if translation == MISSING_TRANSLATION translation = attribute.present? ? attribute.humanize : namespace.humanize end translation end
i18n_scope() 链接
返回类的 i18n_scope。如果需要自定义查找,请覆盖此方法。
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/translation.rb, line 28 def i18n_scope :activemodel end
lookup_ancestors() 链接
当本地化一个字符串时,它会通过此方法返回的查找路径进行查找,该路径用于 ActiveModel::Name#human、ActiveModel::Errors#full_messages 和 ActiveModel::Translation#human_attribute_name。
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/translation.rb, line 36 def lookup_ancestors ancestors.select { |x| x.respond_to?(:model_name) } end