Module: RailsExtend::ActiveRecord::Enum
- Defined in:
- lib/rails_extend/active_record/enum.rb
Class Method Summary collapse
Instance Method Summary collapse
- #enum_i18n(attribute, value) ⇒ Object
- #enum_key(attribute) ⇒ Object
- #help_i18n(attribute) ⇒ Object
- #options_i18n(attribute) ⇒ Object
Class Method Details
.extended(mod) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/rails_extend/active_record/enum.rb', line 55 def self.extended(mod) mod.attribute_method_suffix '_i18n' mod.class_exec do def attribute_i18n(attr) if [:json, :jsonb].include? self.class.columns_hash[attr]&.type send(attr)&.transform_keys! { |key| self.class.human_attribute_name(key) } else self.class.enum_i18n attr, send(attr) end end end end |
Instance Method Details
#enum_i18n(attribute, value) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/rails_extend/active_record/enum.rb', line 31 def enum_i18n(attribute, value) h = ::I18n.t enum_key(attribute), default: {} h.compact! v = nil if h.is_a?(Hash) v = h[value] ? h[value] : h[value.to_s.to_sym] end if v.nil? && value.blank? v = value.to_s end if v.nil? v = human_attribute_name(value) end v end |
#enum_key(attribute) ⇒ Object
51 52 53 |
# File 'lib/rails_extend/active_record/enum.rb', line 51 def enum_key(attribute) RailsExtend.config.enum_key.call(self, attribute) end |
#help_i18n(attribute) ⇒ Object
25 26 27 28 29 |
# File 'lib/rails_extend/active_record/enum.rb', line 25 def help_i18n(attribute) return nil if attribute.blank? help_key = RailsExtend.config.help_key.call(self, attribute) ::I18n.t help_key, default: nil end |
#options_i18n(attribute) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/rails_extend/active_record/enum.rb', line 6 def (attribute) h = ::I18n.t enum_key(attribute), default: {} h.compact! if h.is_a?(Hash) && h.present? return h.invert end if h.blank? name = attribute.to_s.pluralize if respond_to?(name) enum_hash = public_send(name) h = enum_hash.keys.map { |i| [i.humanize, i] }.to_h end end h end |