1

Is there a better way to write this code? He currently creates a hash with the translation for its proper enums.

class ApplicationRecord < ActiveRecord::Base
  def self.translate_enum(enum)
    self.send(enum.to_s).map do |key, value|
      { self.human_enum_name(enum, key) => value }
    end.reduce(:merge)
  end
end

class EnumerableObject < ApplicationRecord
     enum sales_exception: { without: 0, income: 1, commitment: 2, restriction: 3 }, _suffix: true
end

EnumerableObject.translate_enum(:sales_exception)
=> {"Sem Exceção"=>0, "Exceção Renda"=>1, "Exceção Comprometimento"=>2, "Exceção Restrição"=>3}
Alec Rust
  • 10,532
  • 12
  • 48
  • 63

2 Answers2

0

I will prefer to use enumerate_it gem instead of above, as we can define and use translations with this gem. Also is simple, provides scopes, helpers methods and easy to reuse enumeration

Ganesh
  • 1,924
  • 1
  • 18
  • 31
  • Good solution here : https://stackoverflow.com/questions/22827270/how-to-use-i18n-with-rails-4-enums – P.Bra Jun 14 '18 at 00:11
0

Enumerize gem or Translate Enum gem are good options. Both allows you to declare translation in your localization file allowing translation for different languages. Both are very similar to implement, I've used both, the only reason I would use one over the other is the integration with other gems.

Example for the Translate enum gem:

class Post < ActiveRecord::Base
  include TranslateEnum

  enum status: { published: 0, archive: 1 }
  translate_enum :status
end

And in your localization file:

en:
  activerecord:
    attributes:
      post:
        status_list:
          published: Was published
          archive: Was archived
marimaf
  • 5,382
  • 3
  • 50
  • 68