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

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/rails/enum_hash.rb

Overview

This cop 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.'

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/rubocop/cop/rails/enum_hash.rb', line 43

def autocorrect(node)
  hash = node.children.each_with_index.map do |elem, index|
    "#{source(elem)} => #{index}"
  end.join(', ')

  ->(corrector) { corrector.replace(node.loc.expression, "{#{hash}}") }
end

#on_send(node) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/rails/enum_hash.rb', line 32

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)))
    end
  end
end