ruby-on-rails - 为什么 twitter-bootstrap-rails 生成的 View 使用 model_class.human_attribute_name(:column) instead of just a string?

标签 ruby-on-rails twitter-bootstrap generator twitter-bootstrap-rails

安装 twitter-bootstrap-rails 后,使用生成器:

rails g bootstrap:themed Model

创建包含以下行的 View :
  <th><%= model_class.human_attribute_name(:comment_date) %></th>
  <th><%= model_class.human_attribute_name(:comment_time) %></th>

默认的 rails 生成器只是直接插入人类可读的列名:
 <th>Comment date</th>
 <th>Comment time</th>

这使得 View 更清晰,并且在运行时似乎更有效。

twitter-bootstrap-rails 生成的 View 有什么好处吗?

谢谢!

(PS,开发者网站离线,github和google+都不允许发送私信,github上的“问题”和google+帖子上的公开评论似乎都不适合这个问题,所以希望这里的人可能熟悉model_class.human_attribute_name() 的用例

最佳答案

看看它的来源,你就会明白:

# File activemodel/lib/active_model/translation.rb, line 45
def human_attribute_name(attribute, options = {})
  defaults  = []
  parts     = attribute.to_s.split(".", 2)
  attribute = parts.pop
  namespace = parts.pop

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

  defaults << :"attributes.#{attribute}"
  defaults << options.delete(:default) if options[:default]
  defaults << attribute.humanize

  options.reverse_merge! :count => 1, :default => defaults
  I18n.translate(defaults.shift, options)
end
human_attribute_name在本地化属性名称方面做得很好。即使您正在构建仅使用英语的应用程序——谁知道呢,也许您的收件箱已经收到了一封来自您的客户的电子邮件,内容是关于他扩展业务的计划,而这种扩展将包括人们从右到左书写的国家。

这个怎么运作

假设您有 Product型号为 title属性。调用human_attribute_name这边走:
Product.human_attribute_name 'title'

将调用 I18n.t (请参阅上面代码段中的最后一行)具有以下参数:
I18.t 'activerecord.attributes.product.title', {
  :count=>1, 
  :default=>[:"attributes.title", "Title"] 
}

因此,您可以提供特定于某些模型和特定于某些属性名称的翻译。除非您提供任何这些翻译,否则您将获得通过 humanize 创建的属性的英文版本。方法。

关于ruby-on-rails - 为什么 twitter-bootstrap-rails 生成的 View 使用 model_class.human_attribute_name(:column) instead of just a string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972232/

相关文章:

ruby-on-rails - 如何在 unicode 中创建复选标记?

javascript - 通过模态窗口将数据从按钮传递到服务器

javascript - 在 Bootstrap 表上使用 slimscroll 的正确方法是什么?

c# - 正确锁定线程安全的自生成列表 (C#)

c# - 如何使 `await …` 与 `yield return` 一起工作(即在迭代器方法中)?

python - 生成器和函数

javascript - 以随机顺序禁用按钮,Rails/javascript

ruby-on-rails - 如何使will_paginate与液体一起工作

ruby-on-rails - Typus 路由顺序

css - 我的跨度有什么问题