enum supporting i18n translation with "_text" suffix methods?

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

enum supporting i18n translation with "_text" suffix methods?

Martin Hong
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)

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
: 用户
: 性别

# And now you can get enum text with _text suffix:
User.new(sex: "male").sex_text   # => "男"

# Additionaly and optionally, a new class method:
sexes # => { "male" => "男", "female" => "女" }    # with this, you can conveniently use it to render options for a select control in views

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To post to this group, send email to [hidden email].
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.