安装 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/