简体   繁体   中英

This is the best way to translate enum to use in select with I18n?

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}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM