Module: HumanizeEnum::Helpers::ClassMethods

Defined in:
lib/humanize_enum/helpers.rb

Instance Method Summary collapse

Instance Method Details

#check_enum!(enum_name) ⇒ Object

Parameters:

  • enum_name (String, Symbol)

Raises:



59
60
61
# File 'lib/humanize_enum/helpers.rb', line 59

def check_enum!(enum_name)
  raise UnknownEnumKey unless defined_enums.keys.include?(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

Parameters:

  • enum_name (String, Symbol)

    enum name

  • enum_text (String)

    text value of the enum

Returns:

  • (Integer, String, NilClass)


42
43
44
# File 'lib/humanize_enum/helpers.rb', line 42

def dehumanize_enum(enum_name, enum_text)
  humanize_enums(enum_name).invert[enum_text]
end

#enum_options(enum_name) ⇒ Array<SelectOption>

Returns array of structs with :id, :key, :text, :checked.

Parameters:

  • enum_name (String, Symbol)

    enum key to be translated

Returns:

  • (Array<SelectOption>)

    array of structs with :id, :key, :text, :checked

Raises:



49
50
51
52
53
54
55
# File 'lib/humanize_enum/helpers.rb', line 49

def enum_options(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.

Examples:

Payment.humanize_enum(:status, :pending) # => 'Pending'

Parameters:

  • enum_name (String, Symbol)
  • enum_value (String, Symbol)

Returns:

  • (String)

    translated value of an enum

Raises:



17
18
19
20
# File 'lib/humanize_enum/helpers.rb', line 17

def humanize_enum(enum_name, enum_value)
  check_enum!(enum_name)
  I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name}/#{enum_value}")
end

#humanize_enums(enum_name) ⇒ Hash<String, String>

Returns hash where key is enum name and value is its translation.

Examples:

Payment.humanize_enums(:status)
{
  "initial" => "Initial status",
     "paid" => "Payment processed",
    "error" => "Payment error"
}

Returns:

  • (Hash<String, String>)

    hash where key is enum name and value is its translation



30
31
32
33
34
# File 'lib/humanize_enum/helpers.rb', line 30

def humanize_enums(enum_name)
  enum_options(enum_name).map do |enum|
    [enum.value, enum.text]
  end.to_h
end