Rails: How to use i18n with Rails 4 enums

后端 未结 16 2292
天涯浪人
天涯浪人 2020-11-28 04:10

Rails 4 Active Record Enums are great, but what is the right pattern for translating with i18n?

16条回答
  •  时光说笑
    2020-11-28 04:50

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      def self.enum(definitions)
        defind_i18n_text(definitions) if definitions.delete(:_human)
        super(definitions)
      end
    
      def self.defind_i18n_text(definitions)
        scope = i18n_scope
        definitions.each do |name, values|
          next if name.to_s.start_with?('_')
          define_singleton_method("human_#{name.to_s.tableize}") do
            p values
            values.map { |key, _value| [key, I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{key}")] }.to_h
          end
    
          define_method("human_#{name}") do
            I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{send(name)}")
          end
        end
      end
    end
    
    
    en:
      activerecord:
        enums:
          mymodel:
            my_somethings:
               my_enum_value: "My enum Value!"
    
    enum status: [:unread, :down], _human: true
    

提交回复
热议问题