Skip to content

Instantly share code, notes, and snippets.

@repoles
Last active March 21, 2022 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save repoles/e798a915a0df49e3bcce0b7932478728 to your computer and use it in GitHub Desktop.
Save repoles/e798a915a0df49e3bcce0b7932478728 to your computer and use it in GitHub Desktop.
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"
# 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
# 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
# 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