Sha256: 359d394db955ff293ef104b575b3f15b7af33f5c659ed139103f8bfbd60ee8c8

Contents?: true

Size: 1.47 KB

Versions: 17

Compression:

Stored size: 1.47 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Sometimes using dig method ends up with just a single
      # argument. In such cases, dig should be replaced with [].
      #
      # @example
      #   # bad
      #   { key: 'value' }.dig(:key)
      #   [1, 2, 3].dig(0)
      #
      #   # good
      #   { key: 'value' }[:key]
      #   [1, 2, 3][0]
      #
      #   # good
      #   { key1: { key2: 'value' } }.dig(:key1, :key2)
      #   [1, [2, [3]]].dig(1, 1)
      #
      #   # good
      #   keys = %i[key1 key2]
      #   { key1: { key2: 'value' } }.dig(*keys)
      #
      class SingleArgumentDig < Base
        extend AutoCorrector

        MSG = 'Use `%<receiver>s[%<argument>s]` instead of `%<original>s`.'
        RESTRICT_ON_SEND = %i[dig].freeze

        # @!method single_argument_dig?(node)
        def_node_matcher :single_argument_dig?, <<~PATTERN
          (send _ :dig $!splat)
        PATTERN

        def on_send(node)
          return unless node.receiver

          expression = single_argument_dig?(node)
          return unless expression

          receiver = node.receiver.source
          argument = expression.source

          message = format(MSG, receiver: receiver, argument: argument, original: node.source)
          add_offense(node, message: message) do |corrector|
            correct_access = "#{receiver}[#{argument}]"
            corrector.replace(node, correct_access)
          end
        end
      end
    end
  end
end

Version data entries

17 entries across 17 versions & 3 rubygems

Version Path
rubocop-1.21.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.20.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.19.1 lib/rubocop/cop/style/single_argument_dig.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.19.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.18.4 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.18.3 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.18.2 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.18.1 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.18.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.17.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.16.1 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.16.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.15.0 lib/rubocop/cop/style/single_argument_dig.rb
cocRb-0.1.0 .bundle/ruby/3.0.0/gems/rubocop-1.14.0/lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.14.0 lib/rubocop/cop/style/single_argument_dig.rb
rubocop-1.13.0 lib/rubocop/cop/style/single_argument_dig.rb