Class: RuboCop::Cop::Rails::EnumHash

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rails/enum_hash.rb

Overview

Looks for enums written with array syntax.

When using array syntax, adding an element in a position other than the last causes all previous definitions to shift. Explicitly specifying the value for each key prevents this from happening.

Examples:

# bad
enum status: [:active, :archived]

# good
enum status: { active: 0, archived: 1 }

Constant Summary collapse

MSG =
'Enum defined as an array found in `%<enum>s` enum declaration. Use hash syntax instead.'
RESTRICT_ON_SEND =
%i[enum].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/rails/enum_hash.rb', line 34

def on_send(node)
  enum?(node) do |pairs|
    pairs.each do |pair|
      key, array = array_pair?(pair)
      next unless key

      add_offense(array, message: format(MSG, enum: enum_name(key))) do |corrector|
        hash = array.children.each_with_index.map do |elem, index|
          "#{source(elem)} => #{index}"
        end.join(', ')

        corrector.replace(array, "{#{hash}}")
      end
    end
  end
end