ruby-on-railsruby-on-rails-3humanize

Forcing "humanized" names of fields to be lowercase in Rails 3


As far as I know, the accepted way to set the "humanized" names of fields in Rails 3 is to use locales:

# config/locales/en.yml
en:
  activerecord:
    attributes:
      member:
        username: 'username' # rather than 'Username'

However, I simply want Rails 3 to use lowercase versions of its default humanized names. Is there an easy, built-in way to do this?

An example to help clarify: When inside of a form_for, <%= f.label :username %> displays "Username" by default. I want it to display "username".


Solution

  • The label helper defaults to using human_attribute_name to turn an attribute into a human name. If you look at the source, human_attribute_name tries a few things before falling back to attributes.to_s.humanize. It tries the translation first, and then it looks for a :default option in the options hash.

    So, the simplest/best way to get the functionality you want is to override human_attribute_name with your own that provides a :default option and then calls the original. Rails provides a reasonable way to do this sort of thing with alias_method_chain, so...

    I've heard enough, just give me the answer!

    Put the following in any file in config/initializers and restart your app:

    module ActiveModel
      module Translation
        def human_attribute_name_with_foo attribute, options = {}
          human_attribute_name_without_foo attribute, options.merge( :default => attribute.humanize.downcase )
        end
    
        alias_method_chain :human_attribute_name, :foo
      end
    end