Redline Software Inc. - Winnipeg's Leader in Ruby on Rails Development

Human Attribute Override Plugin Tutorial

This is my second tutorial covering the plugins that we’ve developed.

This tutorial covers the human attribute override plugin.

The plugin allows humanized versions of attributes to be overridden with custom strings to provide a better conversion than human_name may provide.

Why?

The main reason for creating this plugin is that Rails doesn’t always provide an acceptable “humanized” version of an attribute name.

1
Column.new('num_employees', ...).human_name # => 'Num employees'

You could argue that perhaps the attribute should be named number_of_employees..

1
Column.new('number_of_employees', ...).human_name # => 'Number of employees'

But this is hardly an acceptable solution for various reasons

1. The attribute name is too wordy.
2. Changing an attribute name for the sake of it’s humanized version reading better results in unneeded refactoring.
3. You’re using a legacy database that uses a specific naming convention.

Rails Usage

Rails uses these humanized conversions in error reporting with the error_messages_for method via full_messages and in schema definitions for column names with the human_name method.

Using the above example, a table companies has a field called “num_employees”.

1
2
3
4
class Company < ActiveRecord::Base
end

Company.columns_hash['num_employees'].human_name # => 'Num employees'

Plugin Usage

So since the column name conversion in the previous example is basically unacceptable, let’s use the plugin to fix this up.

1
2
3
4
5
class Company < ActiveRecord::Base
   attr_human_name 'num_employees' => 'Number of employees'
end

Company.columns_hash['num_employees'].human_name # => 'Number of employees'

The plugin provides an additonal method called attr_human_name that accepts a hash of “attribute name” => “desired humanized conversion text” pairs. The hash keys (the attribute names) can be specified as a string or a symbol.

Specifying more than one conversion…

1
2
3
4
5
6
class Company < ActiveRecord::Base
   attr_human_name :num_employees => 'Number of employees', :unit_num => 'Unit #'
end

Company.columns_hash['num_employees'].human_name # => 'Number of employees'
Company.columns_hash['unit_num'].human_name # => 'Unit #'

If you’d like to retrieve a list of all of the overridden attributes, you can use human_name_attributes

1
Company.human_name_attributes # => {"num_employees"=>"Number of employees", "unit_num"=>"Unit #"}

Summary

So if you have some attributes that need better names for use in your rails views, use the plugin and make your life much easier.

Comments