method

human_attribute_name

Importance_4
v2.2.1 - Show latest stable - 4 notes - Class: ActiveRecord::Base
  • 1.0.0
  • 1.1.6
  • 1.2.6
  • 2.0.3
  • 2.1.0 (0)
  • 2.2.1 (13)
  • 2.3.8 (0)
  • 3.0.0
  • 3.0.9
  • 3.1.0
  • 3.2.1
  • 3.2.8
  • 3.2.13
  • 4.0.2
  • 4.1.8
  • 4.2.1
  • 4.2.7
  • 4.2.9
  • 5.0.0.1
  • 5.1.7
  • 5.2.3
  • 6.0.0
  • 6.1.3.1
  • 6.1.7.7
  • 7.0.0
  • 7.1.3.2
  • 7.1.3.4
  • What's this?
human_attribute_name(attribute_key_name, options = {}) public

Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:

  Person.human_attribute_name("first_name") # => "First name"

This used to be depricated in favor of humanize, but is now preferred, because it automatically uses the I18n module now. Specify options with additional translating options.

Show source
Register or log in to add new notes.
October 24, 2008
2 thanks

The human side of inflections

Rails 2.2 moves this functionality to the Inflector::Inflections class:

See the ticket and the code that allow the humanisation rules to be centralised in an app.

October 23, 2008
2 thanks

Customizing attribute names in error messages

This can be used to customize attribute names in error messages. See my note in ActionView::Helpers::ActiveRecordHelper#error_messages_for.

February 3, 2009
0 thanks

Getting functionality from instances

If you want to get this functionality from instances of the models too, you can easily monkey patch rails to allow this. This is only semi-bad practice, AFAIK.

In config/initializers/overrides.rb:

#
# Wrapper for @model.human_attribute_name -> Model.human_attribute_name
#
class ActiveRecord::Base
  def human_attribute_name(*args)
    self.class.human_attribute_name(*args)
  end
end

Now, why is this bad? Because we change a core class, and that makes maintainability a little bit harder since new developers will not know about this.

The good part is that is such a small thing and as long as human_attribute_name exists in the class, this extension will work.

Example usage:

# index.html.haml
%th= User.human_attribute_name('login')
%th= User.human_attribute_name('email')
# ...

# show.html.haml
%p
  %strong= "#{@user.human_attribute_name('login')}: "
  = @user.login

In this example, about nothing was gained at all, really. A better example is when you are building helpers to do stuff like displaying model attributes for you and whatnot. Examples for this would be far too huge to show off here, but basically, you avoid having to do stuff like this:

if options.include? :model
  model = options[:model]
  model = model.class unless model.is_a? Class
  model.human_attribute_name(field)
else
  # ...
end

and you want to keep your views clean (@user vs. @user.class)

October 11, 2010 - (>= v3.0.0)
0 thanks