Question

I have an User model, which has roles, defined in a module. In short,

class User < ActiveRecord::Base
  (...)
  module Roles
    Admin           = 0
    SuperPrefeitura = 1
    Prefeitura      = 2
    Instituicao     = 3
  end

  def is_admin?
    role == Roles::Admin
  end
  (...)  
end

Nice. Now, I want to show the role of a user, using i18n. A solution would be

def role_name
  case role
  when Roles::Admin
    :admin
  end
  (...)
end

And translate :admin

But it does not look like a good solution.

What is the best way of doing that?

Was it helpful?

Solution

Annnd two months later! :D

There is a gem that solves exactly my problem. enumerize.

Sample usage (from github):

Model:

class User < ActiveRecord::Base
  extend Enumerize

  enumerize :sex, in: [:male, :female]

  enumerize :role, in: [:user, :admin], default: :user
end

locales:

en:
  enumerize:
    user:
      sex:
        male: "Male"
        female: "Female"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top