2016-06-14 39 views
1

Rails自动人性化属性名称。我想将这些人性化名称冠名为案例。例如,MyModel.full_name目前显示为'Full name',但我希望“n”大写:'Full Name'Rails:如何使人性化属性titlecase

我目前在en.yml中定义了多字属性,它根本不是DRY。我想覆盖.humanize.humanize以我想要的方式工作的最佳方式是什么?

奖金的问题:

不幸的是,Rails的.titleize忽略英文名称规则。像'a'和'to'这样的词不应该大写,除非它们是字符串的第一个或最后一个单词。我们如何解决这个问题呢?

MyModel.time_to_failure应该是'Time to Failure'但是MyModel.send_to应该是'Send To'

+0

这可能是有用的:http://stackoverflow.com/questions/2842444/ruby-on-rails-converting-somewordhere-to-some-word-here – apod

+0

['包括HumanAttributeOverride'](https: //gist.github.com/aruprakshit/113ee1e08d8f6efee2ddbbd2644e0463)在每个模型? 'HumanAttributeOverride'是一个关注模块。 –

+0

如果你有足够小的单词数量不会被大写,并且你知道这个集合,那么就像这样做:http://stackoverflow.com/questions/14251311/capitalizing-titles – unflores

回答

1

谢谢您的建议! @Arup Rakshit,你的建议向我指出ActiveModel::Translation#human_attribute_name,这竟然是Rails的4

这里做到这一点的方式是我所做的:


的Gemfile

gem 'titleize' 

config/initializers/human_attribute_name.rb

# Overrides human_attribute_name so model attributes are title case. 
# Combine with the titleize gem which overrides String#titleize with English-language rules. 
module ActiveModel::Translation 
    def human_attribute_name(attribute, options = {}) 
    options = { count: 1 }.merge!(options) 
    parts  = attribute.to_s.split(".") 
    attribute = parts.pop 
    namespace = parts.join("/") unless parts.empty? 
    attributes_scope = "#{self.i18n_scope}.attributes" 

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

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

    options[:default] = defaults 
    I18n.translate(defaults.shift, options) 
    end 
end 

# If you're using Rails enums and the enum_help gem to make them translatable, use this code to default to titleize instead of humanize 
module EnumHelp::Helper 
    def self.translate_enum_label(klass, attr_name, enum_label) 
    ::I18n.t("enums.#{klass.to_s.underscore.gsub('/', '.')}.#{attr_name}.#{enum_label}", default: enum_label.titleize) 
    end 
end 

如果你不使用枚举和enum_help,删除最后一位。

一个问题也可以发挥作用,但在我的项目中,没有理由不将它应用于每个模型。

美丽!