Last active
March 21, 2022 14:08
-
-
Save repoles/e798a915a0df49e3bcce0b7932478728 to your computer and use it in GitHub Desktop.
i18n with Rails 4 enums (https://stackoverflow.com/a/36335591/2640073)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Business.human_enum_name(:kind, :company) #=> "Pessoa juridíca" | |
Business.human_enum_name(:kind, :person) #=> "Pessoa física" | |
Business.human_enum_name(:status, :active) #=> "Ativa" | |
Business.human_enum_name(:status, :inactive) #=> "Inativa" | |
Business.human_enum_name(:status, :closed) #=> "Fechada" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# models/application_record.rb | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
def self.human_enum_name(enum_name, enum_value) | |
model_name_i18n_key = model_name.i18n_key | |
pluralized_enum_name = enum_name.to_s.pluralize | |
defaults = [] | |
defaults << :"activerecord.attributes.#{model_name_i18n_key}.#{pluralized_enum_name}.#{enum_value}" | |
defaults << :"attributes.#{pluralized_enum_name}.#{enum_value}" | |
defaults << enum_value.to_s.humanize | |
I18n.t(defaults.shift, default: defaults) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# models/business.rb | |
class Business < ApplicationRecord | |
enum kind: { company: 'company', person: 'person' }, _default: 'company' | |
enum status: { active: 'active', inactive: 'inactive', closed: 'closed' }, _default: 'active' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/pt-BR.yml | |
pt-BR: | |
activerecord: | |
attributes: | |
business: | |
kinds: | |
company: "Pessoa jurídica" | |
person: "Pessoa física" | |
statuses: | |
active: "Ativa" | |
inactive: "Inativa" | |
closed: "Fechada" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment