Translating attribute values in Rails: human_attribute_values
Some model attributes in the project I’m working on have values which have to be mapped in the views. There are boolean values and enums which are not really meaningful as is.
Rails already provides built in support for mapping attribute and model names via
Model.human_attribute_name. Because they use the I18n API you can specify different translations for each locale.
Now, to map values, we could write helpers doing that. But to have the same flexibility, we would need to somehow use the I18n API, too. Instead of doing this in our custom application code, I thought it would be nice to have a similar mechanism for values on models and instances. Maybe something like
human_attribute_value. So I wrote my first tiny gem: human_attribute_values.
Following the conventions of the built in translation mechanisms, the translations are first looked up under
values.attribute_name.value and if there is no translation found, the stringified value itself is returned.
I see the primary use case in translating booleans and enums, but it also supports numbers and, of course, strings. A bonus is the way STI models are handled: Rails steps up through the translations for ancestors until it finds a mapping.
The implementation is a small adjustment to the code of human_attribute_name. Because of this I’ll probably have to find a way to provide different implementations for different Rails versions someday.