Sha256: 93de18c729f321e2765c15cf9bf94158f5230c9f1e264fb3b2b0d4837aafe94a

Contents?: true

Size: 1.65 KB

Versions: 14

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Checks for lambdas and procs that always return nil,
      # which can be replaced with an empty lambda or proc instead.
      #
      # @example
      #   # bad
      #   -> { nil }
      #
      #   lambda do
      #     next nil
      #   end
      #
      #   proc { nil }
      #
      #   Proc.new do
      #     break nil
      #   end
      #
      #   # good
      #   -> {}
      #
      #   lambda do
      #   end
      #
      #   -> (x) { nil if x }
      #
      #   proc {}
      #
      #   Proc.new { nil if x }
      #
      class NilLambda < Base
        extend AutoCorrector
        include RangeHelp

        MSG = 'Use an empty %<type>s instead of always returning nil.'

        # @!method nil_return?(node)
        def_node_matcher :nil_return?, <<~PATTERN
          { ({return next break} nil) (nil) }
        PATTERN

        def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
          return unless node.lambda? || node.proc?
          return unless nil_return?(node.body)

          message = format(MSG, type: node.lambda? ? 'lambda' : 'proc')
          add_offense(node, message: message) do |corrector|
            autocorrect(corrector, node)
          end
        end

        private

        def autocorrect(corrector, node)
          range = if node.single_line?
                    range_with_surrounding_space(node.body.loc.expression)
                  else
                    range_by_whole_lines(node.body.loc.expression, include_final_newline: true)
                  end

          corrector.remove(range)
        end
      end
    end
  end
end

Version data entries

14 entries across 12 versions & 3 rubygems

Version Path
cm-admin-1.5.22 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/nil_lambda.rb
cm-admin-1.5.21 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/nil_lambda.rb
cm-admin-1.5.20 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/nil_lambda.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/nil_lambda.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.36.0/lib/rubocop/cop/style/nil_lambda.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/nil_lambda.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.36.0/lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.39.0 lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.38.0 lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.37.1 lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.37.0 lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.36.0 lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.35.1 lib/rubocop/cop/style/nil_lambda.rb
rubocop-1.35.0 lib/rubocop/cop/style/nil_lambda.rb