Sha256: 9986e9685c7e026bedaa2f6cf65f8c52d60724c1e1f47b8f879c764099f0ca39

Contents?: true

Size: 1.81 KB

Versions: 10

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # 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.
      #
      # @example
      #   # bad
      #   enum status: [:active, :archived]
      #
      #   # good
      #   enum status: { active: 0, archived: 1 }
      #
      class EnumHash < Cop
        MSG = 'Enum defined as an array found in `%<enum>s` enum declaration. '\
              'Use hash syntax instead.'

        def_node_matcher :enum?, <<~PATTERN
          (send nil? :enum (hash $...))
        PATTERN

        def_node_matcher :array_pair?, <<~PATTERN
          (pair $_ $array)
        PATTERN

        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

        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

        private

        def enum_name(key)
          case key.type
          when :sym, :str
            key.value
          else
            key.source
          end
        end

        def source(elem)
          case elem.type
          when :str
            elem.value.dump
          when :sym
            elem.value.inspect
          else
            elem.source
          end
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
rubocop-rails-2.8.1 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.8.0 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.7.1 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.7.0 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.6.0 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.5.2 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.5.1 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.5.0 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.4.2 lib/rubocop/cop/rails/enum_hash.rb
rubocop-rails-2.4.1 lib/rubocop/cop/rails/enum_hash.rb