Sha256: c9084122facf9793a97ec097b4026d46a36053767059828b41d71dbcbb0b4f31

Contents?: true

Size: 1.68 KB

Versions: 10

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Checks for useless method definitions, specifically: empty constructors
      # and methods just delegating to `super`.
      #
      # @safety
      #   This cop is unsafe as it can register false positives for cases when an empty
      #   constructor just overrides the parent constructor, which is bad anyway.
      #
      # @example
      #   # bad
      #   def initialize
      #     super
      #   end
      #
      #   def method
      #     super
      #   end
      #
      #   # good - with default arguments
      #   def initialize(x = Object.new)
      #     super
      #   end
      #
      #   # good
      #   def initialize
      #     super
      #     initialize_internals
      #   end
      #
      #   def method(*args)
      #     super(:extra_arg, *args)
      #   end
      #
      class UselessMethodDefinition < Base
        extend AutoCorrector

        MSG = 'Useless method definition detected.'

        def on_def(node)
          return if use_rest_or_optional_args?(node)
          return unless delegating?(node.body, node)

          add_offense(node) { |corrector| corrector.remove(node) }
        end
        alias on_defs on_def

        private

        def use_rest_or_optional_args?(node)
          node.arguments.any? { |arg| arg.restarg_type? || arg.optarg_type? || arg.kwoptarg_type? }
        end

        def delegating?(node, def_node)
          if node&.zsuper_type?
            true
          elsif node&.super_type?
            node.arguments.map(&:source) == def_node.arguments.map(&:source)
          else
            false
          end
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 3 rubygems

Version Path
call_your_name-0.1.0 vendor/bundle/ruby/3.1.0/gems/rubocop-1.48.1/lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.48.1 lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.48.0 lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.47.0 lib/rubocop/cop/lint/useless_method_definition.rb
zilla-0.2.0 vendor/bundle/ruby/3.2.0/gems/rubocop-1.46.0/lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.46.0 lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.45.1 lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.45.0 lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.44.1 lib/rubocop/cop/lint/useless_method_definition.rb
rubocop-1.44.0 lib/rubocop/cop/lint/useless_method_definition.rb