I use ActiveRecord enums in my applications and it is common to display human readable text for enum values. For example, I have a class with an enum named sex:
class User < ApplicationRecord enum sex: %w(male female) end
``
And I need to display translated text “男” for “male” and “女” for “female” in views.
I searched official document and StackOverflow and found no any i18n translation pattern for Rails’ enum. I thought enum should be regarded like attributes.
Inspired by enumerize, which provides a mechanism to access enum’s human readable text with _text suffix methods. Maybe Rails could also provide similar methods?
I am planing to open a feature PR to support this, but I am looking forward to get more discussion from you.
In my implementation, I will define a i18n pattern for enum and provide a new method like what enumerize did, the below shows my assumption:
translations
zh-CN: activerecord: models: user: 用户 attributes: user: sex: 性别 enums: user: sex: male: 男 female: 女
``
And now you can get enum text with _text suffix:
User.new(sex: “male”).sex_text # => “男”
Additionaly and optionally, a new class method:
User.humanized_sexes # => { “male” => “男”, “female” => “女” } # with this, you can conveniently use it to render options for a select control in views
``