Module: HumanizeEnum::ClassMethods
- Defined in:
- lib/humanize_enum/class_methods.rb
Instance Method Summary collapse
- #check_enum!(enum_name) ⇒ Object
-
#dehumanize_enum(enum_name, enum_text) ⇒ Integer, ...
Get enum value from a translated enum text.
-
#enum_options(enum_name) ⇒ Array<SelectOption>
Array of structs with :id, :key, :text, :checked.
-
#humanize_enum(enum_name, enum_value) ⇒ String
Translated value of an enum.
-
#humanize_enums(enum_name) ⇒ Hash<String, String>
Hash where key is enum name and value is its translation.
Instance Method Details
#check_enum!(enum_name) ⇒ Object
51 52 53 54 |
# File 'lib/humanize_enum/class_methods.rb', line 51 def check_enum!(enum_name) return unless HumanizeEnum.configuration.check_defined_enums raise UnknownEnumKey unless defined_enums.has_key?(enum_name.to_s) end |
#dehumanize_enum(enum_name, enum_text) ⇒ Integer, ...
Get enum value from a translated enum text. Useful for parsing incoming i18n-ed text labels that were generated by humanize_enum
34 35 36 |
# File 'lib/humanize_enum/class_methods.rb', line 34 def dehumanize_enum(enum_name, enum_text) humanize_enums(enum_name).key(enum_text)&.underscore end |
#enum_options(enum_name) ⇒ Array<SelectOption>
Returns array of structs with :id, :key, :text, :checked.
41 42 43 44 45 46 47 |
# File 'lib/humanize_enum/class_methods.rb', line 41 def (enum_name) check_enum!(enum_name) enum_i18n_key = enum_name.to_s.pluralize send(enum_i18n_key).map do |key, val| SelectOption.new(val, key, humanize_enum(enum_name, key), nil) end end |
#humanize_enum(enum_name, enum_value) ⇒ String
Returns translated value of an enum.
9 10 11 12 |
# File 'lib/humanize_enum/class_methods.rb', line 9 def humanize_enum(enum_name, enum_value) check_enum!(enum_name) I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name}/#{enum_value.to_s.underscore}") end |
#humanize_enums(enum_name) ⇒ Hash<String, String>
Returns hash where key is enum name and value is its translation.
22 23 24 25 26 |
# File 'lib/humanize_enum/class_methods.rb', line 22 def humanize_enums(enum_name) (enum_name).map do |enum| [enum.value, enum.text] end.to_h end |