Using ActiveModel translation with PORO
Coding the API project that I talked about in this post, I wanted to translate the Bmi attributes to Portuguese in the validation error message.
So I searched how to use i18n to translate the attributes of a PORO.
I discovered I could use ActiveModel::Translation because it integrates
the object and Rails internationalization (i18n) framework.
To do so, I implemented this line in my code:
class Bmi
extend ActiveModel::TranslationThen, I created the yml file bmi.yml with
the following configuration:
pt-BR:
activemodel:
attributes:
imc:
height: Altura
weight: PesoThis configuration is very similar to the translation using ActiveRecord,
replacing the name activerecord with activemodel.
So, for example, if you create an instance object with the following parameters:
bmi = Bmi.new(height: 0, weight: 76)Validating the object the message error will be:
bmi.valid? #=> false
bmi.errors.full_messages #=> ["Altura deve ser maior que 0"]With the BMI attribute translated.