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 }

# 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



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rubocop/cop/rails/enum_hash.rb', line 44

def on_send(node)
  target_rails_version >= 7.0 && enum_with_array?(node) do |key, array|
    add_offense(array, message: message(key)) do |corrector|
      corrector.replace(array, build_hash(array))
    end
  end

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

      add_offense(array, message: message(key)) do |corrector|
        corrector.replace(array, build_hash(array))
      end
    end
  end
end