Rails 4 Active Record Enums are great, but what is the right pattern for translating with i18n?
Model:
enum stage: { starting: 1, course: 2, ending: 3 }
def self.i18n_stages(hash = {})
stages.keys.each { |key| hash[I18n.t("checkpoint_stages.#{key}")] = key }
hash
end
Locale:
checkpoint_stages:
starting: Saída
course: Percurso
ending: Chegada
And on the view (.slim):
= f.input_field :stage, collection: Checkpoint.i18n_stages, as: :radio_buttons
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.enum(definitions)
defind_i18n_text(definitions) if definitions.delete(:_human)
super(definitions)
end
def self.defind_i18n_text(definitions)
scope = i18n_scope
definitions.each do |name, values|
next if name.to_s.start_with?('_')
define_singleton_method("human_#{name.to_s.tableize}") do
p values
values.map { |key, _value| [key, I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{key}")] }.to_h
end
define_method("human_#{name}") do
I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{send(name)}")
end
end
end
end
en:
activerecord:
enums:
mymodel:
my_somethings:
my_enum_value: "My enum Value!"
enum status: [:unread, :down], _human: true
I didn't find any specific pattern either, so I simply added:
en:
user_status:
active: Active
pending: Pending...
archived: Archived
to an arbitrary .yml file. Then in my views:
I18n.t :"user_status.#{user.status}"
To keep the internationalization similar as any other attribute I followed the nested attribute way as you can see here.
If you have a class User
:
class User < ActiveRecord::Base
enum role: [ :teacher, :coordinator ]
end
And a yml
like this:
pt-BR:
activerecord:
attributes:
user/role: # You need to nest the values under model_name/attribute_name
coordinator: Coordenador
teacher: Professor
You can use:
User.human_attribute_name("role.#{@user.role}")