ActsEnumTranslable convention translate enums with .yml file.
I hope this functionality is accepted in the pull request I made in the rails project. If it is accepted, we will soon have a merge for rails 5.x. Pull Request in to Rails 5.x
- Install Gem
- Configure enum native Rails
- Add acts_enum_translable in Model class
- Configure active_record attributes in file .yml
- Use methods
Add this line to your application's Gemfile:
gem 'acts_enum_translable'
After:
$ bundle install
More details, please visit ActiveRecord::Enum
# example model
# user.rb
class User < ApplicationRecord
enum status: { inactive: 0, active: 1, blocked: 2 }
enum visible: [:hide, :show]
end
Add in Model for inherit methods
# exemple model
# user.rb
class User < ApplicationRecord
enum status: { inactive: 0, active: 1, blocked: 2 }
enum visible: [:hide, :show]
# Add in Model for inherit methods
acts_enum_translable
end
More details, please visit section 4.5 Translations for Active Record Models
Configure Locale English for exemple
# config/locales/en.activerecord.yml
en:
activerecord:
attributes:
users:
status:
inactive: "Inactive"
active: "Active"
blocked: "Blocked"
visible:
hide: 'Hide'
show: 'Show'
Configure Locale Portuguese for exemple
# config/locales/pt.activerecord.yml
pt:
activerecord:
attributes:
users:
status:
inactive: "Inativo"
active: "Ativo"
blocked: "Bloqueado"
visible:
hide: 'Oculto'
show: 'VisÃvel'
# print status
user = User.new(status: :blocked, visible: :show)
user.status_translable
# english: Blocked
# portuguese: Bloqueado
# print visible
user.visible_translable
# english: Show
# portuguese: VisÃvel
Required key param.
# return Array with Values
# in english
# I18n.locale = :en
User.enum_list(:status)
# => ["Inactive", "Active", "Blocked"]
# in portuguese
# I18n.locale = :pt
User.enum_list(:status)
# => ["Inativo", "Ativo", "Bloqueado"]
Now return array with values and keys or reverse
# return Arrary with par [value, key]
# in english
# I18n.locale = :en
User.enum_with_keys(:status)
# => [["Inactive", 0], ["Active", 1], ["Blocked", 2]]
# in portuguese
# I18n.locale = :pt
User.enum_with_keys(:status)
# => [["Inativo", 0], ["Ativo", 1], ["Bloqueado", 2]]
# return par array [key, value]
User.enum_form(:status)
# => [[0, "Inativo"], [1, "Ativo"], [2, "Bloqueado"]]
Easy return enums translated.
# with I18n.locale = :pt or :en
<%= f.select :status, User.enum_form(:status), include_blank: true %>
We have a long list of valued contributors. Check them all at: https://github.com/Thadeu/acts_enum_translable.
The gem is available as open source under the terms of the MIT License.