DEV Community

Juraj Kostolanský
Juraj Kostolanský

Posted on • Originally published at kostolansky.sk on

2 1

Localize your Rails enums

When Rails 4.1 was released, it came out with a bunch of new features. One of those was ActiveRecord enums.

class Conversation < ApplicationRecord
  enum status: [:active, :archived]
end

conversation = Conversation.create(status: :active)
conversation.status # => "active"
Enter fullscreen mode Exit fullscreen mode

This is a handy feature. However, if you try to localize your Rails app, for example for some select boxes, or just to show the current value, you will quickly realize that there is no built-in feature to translate the enum values.

Starting from Rails 5, all models will inherit from ApplicationRecord. We can use that to create our universal solution.

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def human_enum_name(enum_name, enum_value)
    enum_i18n_key = enum_name.to_s.pluralize
    I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_i18n_key}.#{enum_value}")
  end
end
Enter fullscreen mode Exit fullscreen mode

This little method allows us to use the locale files in the following way:

en:
  activerecord:
    attributes:
      conversation:
        statuses:
          active: Active conversation
          archived: Archived conversation
Enter fullscreen mode Exit fullscreen mode

Then, we can simply use the class method human_enum_name:

Conversation.human_enum_name(:status, :active) # => "Active conversation"
Enter fullscreen mode Exit fullscreen mode

And with an instance:

conversation = Conversation.create(status: :active)
Conversation.human_enum_name(:status, conversation.status) # => "Active conversation"
Enter fullscreen mode Exit fullscreen mode

Actually, I use this approach quite often, so I've built a little gem called human_enum_name. Feel free to use it!

And, if you want to manage your YAML translation files in a clever way, check out my project LocaleData.com.


Original article: Localize your Rails enums

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more