enum supporting i18n translation with "_text" suffix methods?

23 views
Skip to first unread message

Martin Hong

unread,
Oct 18, 2017, 8:47:20 AM10/18/17
to Ruby on Rails: Core
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
Reply all
Reply to author
Forward
0 new messages