Module: EnumHumanizable::ClassMethods

Defined in:
app/models/concerns/enum_humanizable.rb

Instance Method Summary collapse

Instance Method Details

#enum_for_select(attribute) ⇒ Object


32
33
34
35
# File 'app/models/concerns/enum_humanizable.rb', line 32

def enum_for_select(attribute)
  selections = const_get(attribute.to_s.pluralize.upcase)
  selections.map { |k, v| [human_enum_value(attribute, k), k] }
end

#human_enum_value(attribute, value, options = {}) ⇒ Object


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/models/concerns/enum_humanizable.rb', line 6

def human_enum_value(attribute, value, options = {})
  options   = { count: 1 }.merge!(options)
  parts     = attribute.to_s.split(".")
  attribute = parts.pop.pluralize
  namespace = parts.join("/") unless parts.empty?
  attributes_scope = "#{self.i18n_scope}.attributes"

  if namespace
    defaults = lookup_ancestors.map do |klass|
      :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}.#{value}"
    end
    defaults << :"#{attributes_scope}.#{namespace}.#{attribute}.#{value}"
  else
    defaults = lookup_ancestors.map do |klass|
      :"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}.#{value}"
    end
  end

  defaults << :"attributes.#{attribute}.#{value}"
  defaults << options.delete(:default) if options[:default]
  defaults << value.to_s.humanize

  options[:default] = defaults
  I18n.translate(defaults.shift, options)
end