Enumlingo is a simple gem that helps you translate enum values in your Rails app.
extend Enumlingo
in your model and call enumlingo with the enums you want to translate.
class Product < ApplicationRecord
extend Enumlingo
enum status: %i[active inactive]
enum kind: %i[book food medical other]
enumlingo :status, :kind
end
define the translations in your locale file
en:
activerecord:
attributes:
product:
statuses:
active: "Active"
inactive: "Inactive"
kinds:
book: "Book"
food: "Food"
medical: "Medical"
other: "Other"
"zh-CN":
activerecord:
attributes:
product:
statuses:
active: "激活"
inactive: "未激活"
kinds:
book: "书籍"
food: "食品"
medical: "医疗"
other: "其他"
product = Product.new(status: :active, kind: :book)
product.status_lingo # => "Active"
product.kind_lingo # => "Book"
I18n.locale = "zh-CN"
product.status_lingo # => "激活"
product.kind_lingo # => "书籍"
# Translate options with key
Product.statuses_lingo # => [["Active", "active"], ["Inactive", "inactive"]]
Product.kinds_lingo # => [["Book", "book"], ["Food", "food"], ["Medical", "medical"], ["Other", "other"]]
# Translate options with value
Product.statuses_lingo_values # => [["Active", 0], ["Inactive", 1]]
Product.kinds_lingo_values # => [["Book", 0], ["Food", 1], ["Medical", 2], ["Other", 3]]
Product.status_lingo(:active) # => "Active"
<%= form_for @product do |f| %>
<%= f.select :status, Product.statuses_lingo %>
<%= f.select :kind, Product.kinds_lingo %>
...
<% end %>
Add this line to your application's Gemfile:
gem "enumlingo"
And then execute:
$ bundle
Or install it yourself as:
$ gem install enumlingo
Contribution directions go here.
The gem is available as open source under the terms of the MIT License.